コード例 #1
0
ファイル: AgentTests.cs プロジェクト: ly774508966/tofu3d
        public void AgentShouldInjectDependencies()
        {
            ContentInjectablePayload payload = new ContentInjectablePayload();

            payload.Add("FactionContainer", new FactionContainer());
            payload.Add("EventContext", new EventContext());
            payload.Add("AIBehaviourManager", new AIBehaviourManager());
            payload.Add("PathRequestService", new PathRequestService());

            Agent agent = new Agent();
            //agent.InjectDependencies(payload);
            //Pass if fine
        }
コード例 #2
0
        /*
         * ResolveServiceBindings ensures that the class has access to all serviceContext it needs.
         * To set a binding, declare it with a [Dependency] attribute on a protected field. If a
         * service is to be bound to a specialized string, use [Dependency("SpecialName")]
         */
        public virtual void ResolveServiceBindings()
        {
            Type t = GetType();

            if (ServiceContext == null)
            {
                Debug.Log("Service context not bound in " + t.Name);
                return;
            }

            var dependencyFields = t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
                                   .Where(p => (p.GetCustomAttributes(typeof(Dependency), false)).Any());

            foreach (var fieldInfo in dependencyFields)
            {
                object[] atts = fieldInfo.GetCustomAttributes(typeof(Dependency), false);

                string name = ((Dependency)atts[0]).Name;
                if (name == null)
                {
                    name = fieldInfo.FieldType.Name;
                }

                if (ServiceContext.Has(name))
                {
                    fieldInfo.SetValue(this, ServiceContext.Fetch(name));
                }
                else
                {
                    Debug.Log("Can't find service with name " + name + " to bind to " + t.Name);
                }
            }


            ContentInjectables = new ContentInjectablePayload();
            var contentInjectableFields = GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
                                          .Where(p => (p.GetCustomAttributes(typeof(ContentInjectable.ContentInjectable), false)).Any());

            foreach (var fieldInfo in contentInjectableFields)
            {
                string name = fieldInfo.FieldType.Name;

                if (fieldInfo.GetValue(this) == null || !(fieldInfo.GetValue(this) is IContentInjectable))
                {
                    Debug.Log("Trying to set " + name + " as a ContentInjectable in " + this.ToString() + " but it is null or doesn't implement IContentInjectable.");
                }

                ContentInjectables.Add(fieldInfo.FieldType.Name, fieldInfo.GetValue(this) as IContentInjectable);
            }
        }