Ejemplo n.º 1
0
        private InjectMethod getInjectMethod(MemberInfo memberInfo)
        {
            foreach (Attribute attr in memberInfo.GetCustomAttributes(true))
            {
                InjectAttribute inject = attr as InjectAttribute;

                if (inject != null)
                {
                    // if an inject method was clearly specified
                    if (!InjectMethod.None.Equals(inject.InjectMethod))
                    {
                        return(inject.InjectMethod);
                    }
                    if (MemberTypes.Property.Equals(memberInfo.MemberType))
                    {
                        return(InjectMethod.Setter);
                    }
                    if (MemberTypes.Constructor.Equals(memberInfo.MemberType))
                    {
                        return(InjectMethod.Constructor);
                    }

                    return(InjectMethod.Field);
                }
            }

            // never inject it
            return(InjectMethod.None);
        }
Ejemplo n.º 2
0
 private static void FillPropIfIsRefType(PropertyInfo item, InjectAttribute inj, Property prop)
 {
     if (item.PropertyType.IsGenericType)
     {
         if (item.PropertyType.GetGenericTypeDefinition() == typeof(List <>))
         {
             prop.SetList  = inj.ValueToInject as string;
             prop.ListType = item.PropertyType.GetGenericArguments()[0].GetType().ToString();
         }
         else
         {
             prop.SetDictionary = inj.ValueToInject as string;
             prop.KeyType       = item.PropertyType.GetGenericArguments()[0].GetType().ToString();
             prop.ValueType     = item.PropertyType.GetGenericArguments()[1].GetType().ToString();
         }
     }
     else
     {
         if (inj.IsObjectDefinition)
         {
             prop.SetWithObjectDefinition = inj.ValueToInject as string;
         }
         else // is a setWithNewType
         {
             prop.SetWithNewType = inj.ValueToInject as string;
             prop.FileName       = inj.ValueToInject.GetType().Assembly.FullName;
         }
     }
 }
Ejemplo n.º 3
0
        private TClass CreateConstructorInjection <TClass>()
        {
            Type desireClass = typeof(TClass);

            if (desireClass == null)
            {
                return(default(TClass));
            }

            ConstructorInfo[] constructors = desireClass.GetConstructors();

            foreach (var constructor in constructors)
            {
                if (!this.CheckForConstructorInjection <TClass>())
                {
                    continue;
                }

                InjectAttribute inject = (InjectAttribute)constructor
                                         .GetCustomAttributes(typeof(InjectAttribute), true)
                                         .FirstOrDefault();
                ParameterInfo[] parameterTypes    = constructor.GetParameters();
                object[]        constructorParams = new object[parameterTypes.Length];
                int             index             = 0;

                foreach (ParameterInfo parameterType in parameterTypes)
                {
                    NamedAttribute namedAttribute = parameterType.GetCustomAttribute <NamedAttribute>(true);
                    Type           dependancy     = null;

                    if (namedAttribute == null)
                    {
                        dependancy = this.module.GetMapping(parameterType.ParameterType, inject);
                    }
                    else
                    {
                        dependancy = this.module.GetMapping(parameterType.ParameterType, namedAttribute);
                    }

                    if (parameterType.ParameterType.IsAssignableFrom(dependancy))
                    {
                        object instance = this.module.GetInstance(dependancy);

                        if (instance == null)
                        {
                            instance = Activator.CreateInstance(dependancy);
                            this.module.SetInstance(parameterType.ParameterType, instance);
                        }

                        constructorParams[index++] = instance;
                    }
                }

                return((TClass)Activator.CreateInstance(desireClass, constructorParams));
            }

            return(default(TClass));
        }
Ejemplo n.º 4
0
        private static InjectAttribute GetAttribute()
        {
            Assembly        assembly  = Assembly.GetCallingAssembly();
            Type            classType = assembly.GetTypes().FirstOrDefault(x => x == typeof(Weapon));
            InjectAttribute attribute =
                (InjectAttribute)classType.GetCustomAttributes().FirstOrDefault(x => x.GetType() == typeof(InjectAttribute));

            return(attribute);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 获取依赖解决结果
        /// </summary>
        /// <param name="makeServiceBindData">服务绑定数据</param>
        /// <param name="paramInfo">服务实例的参数信息</param>
        /// <param name="param">输入的构造参数列表</param>
        /// <returns>服务所需参数的解决结果</returns>
        /// <exception cref="RuntimeException">生成的实例类型和需求类型不一致</exception>
        private object[] GetDependencies(BindData makeServiceBindData, IList <ParameterInfo> paramInfo, IList <object> param)
        {
            var myParam = new List <object>();

            for (var i = 0; i < paramInfo.Count; i++)
            {
                var info = paramInfo[i];
                if (param != null && i < param.Count)
                {
                    if (info.ParameterType.IsInstanceOfType(param[i]))
                    {
                        myParam.Add(param[i]);
                        continue;
                    }
                }

                var             needService = info.ParameterType.ToString();
                InjectAttribute injectAttr  = null;
                if (info.IsDefined(injectTarget, false))
                {
                    var propertyAttrs = info.GetCustomAttributes(injectTarget, false);
                    if (propertyAttrs.Length > 0)
                    {
                        injectAttr = (InjectAttribute)propertyAttrs[0];
                        if (!string.IsNullOrEmpty(injectAttr.Alias))
                        {
                            needService = injectAttr.Alias;
                        }
                    }
                }

                object instance;
                if (info.ParameterType.IsClass || info.ParameterType.IsInterface)
                {
                    instance = ResloveClass(makeServiceBindData, needService);
                }
                else
                {
                    instance = ResolveNonClass(makeServiceBindData, needService);
                }

                if (injectAttr != null && injectAttr.Required && instance == null)
                {
                    throw new RuntimeException("[" + makeServiceBindData.Service + "] Required [" + makeServiceBindData.Service + "] Service.");
                }

                if (instance != null && !info.ParameterType.IsInstanceOfType(instance))
                {
                    throw new RuntimeException("[" + makeServiceBindData.Service + "] Attr inject type must be [" + info.ParameterType + "] , But instance is [" + instance.GetType() + "] Make service is [" + needService + "].");
                }

                myParam.Add(instance);
            }

            return(myParam.ToArray());
        }
        public static IServiceCollection RegisterType(
            this IServiceCollection serviceCollection,
            Type type,
            InjectAttribute injectAttribute)
        {
            switch (injectAttribute.Type)
            {
            case RegistrationType.AsImplementedInterfaces:
            {
                var implementedInterfaces = type.GetDirectlyImplementedInterfacesSet().ToList();

                foreach (var implementedInterface in implementedInterfaces)
                {
                    switch (injectAttribute.Scope)
                    {
                    case RegistrationScope.Singleton:
                    {
                        serviceCollection.AddSingleton(implementedInterface, type);
                        break;
                    }

                    case RegistrationScope.Transient:
                    {
                        serviceCollection.AddTransient(implementedInterface, type);
                        break;
                    }
                    }
                }

                break;
            }

            case RegistrationType.AsSelf:
            {
                switch (injectAttribute.Scope)
                {
                case RegistrationScope.Singleton:
                {
                    serviceCollection.AddSingleton(type);
                    break;
                }

                case RegistrationScope.Transient:
                {
                    serviceCollection.AddTransient(type);
                    break;
                }
                }

                break;
            }
            }

            return(serviceCollection);
        }
Ejemplo n.º 7
0
        public virtual string GetParamInjectDependency(ParameterInfo paramInfo)
        {
            if (Attribute.IsDefined(paramInfo, typeof(InjectAttribute)))
            {
                InjectAttribute injectTypeAttribute = Attribute.GetCustomAttributes(paramInfo, typeof(InjectAttribute))
                                                      .FirstOrDefault() as InjectAttribute;

                return(injectTypeAttribute.Type.GetDependencyId());
            }

            return(null);
        }
        public Type GetMatchingInterfaceType(Type implementationType, InjectAttribute injectAttribute)
        {
            var matchingInterfaceName = $"I{implementationType.GetTypeInfo().Name}";
            var serviceType           = implementationType.GetInterface(matchingInterfaceName);

            if (serviceType == null)
            {
                throw new ArgumentException($"Class {implementationType} has no matching interface {matchingInterfaceName} defined", nameof(implementationType));
            }

            return(serviceType);
        }
Ejemplo n.º 9
0
        private TClass CreateFieldInjection <TClass>()
        {
            Type desireClass         = typeof(TClass);
            var  desireClassInstance = this.module.GetInstance(desireClass);

            if (desireClassInstance == null)
            {
                desireClassInstance = Activator.CreateInstance(desireClass);
                this.module.SetInstance(desireClass, desireClassInstance);
            }

            FieldInfo[] fields = desireClass.GetFields((BindingFlags)62);
            foreach (var field in fields)
            {
                if (field.GetCustomAttributes(typeof(InjectAttribute), true).Any())
                {
                    Type dependency = null;
                    Type fieldType  = field.FieldType;

                    InjectAttribute injectAttribute = (InjectAttribute)field
                                                      .GetCustomAttributes(typeof(InjectAttribute), true)
                                                      .FirstOrDefault();

                    NamedAttribute namedAttribute = (NamedAttribute)field
                                                    .GetCustomAttribute(typeof(NamedAttribute), true);

                    if (namedAttribute == null)
                    {
                        dependency = this.module.GetMapping(fieldType, injectAttribute);
                    }
                    else
                    {
                        dependency = this.module.GetMapping(fieldType, namedAttribute);
                    }

                    if (fieldType.IsAssignableFrom(dependency))
                    {
                        object instance = this.module.GetInstance(dependency);

                        if (instance == null)
                        {
                            instance = Activator.CreateInstance(dependency);
                            this.module.SetInstance(dependency, instance);
                        }
                        field.SetValue(desireClassInstance, instance);
                    }
                }
            }
            return((TClass)desireClassInstance);
        }
Ejemplo n.º 10
0
        public Task <IBinding> TryCreateAsync(BindingProviderContext context)
        {
            //Get the resolver starting with method then class
            MethodInfo method = context.Parameter.Member as MethodInfo;
            DependencyInjectionConfigAttribute attribute = method.DeclaringType.GetCustomAttribute <DependencyInjectionConfigAttribute>();

            if (attribute == null)
            {
                throw new MissingAttributeException();
            }
            //Initialize DependencyInjection
            Activator.CreateInstance(attribute.Config);
            //Check if there is a name property
            InjectAttribute injectAttribute = context.Parameter.GetCustomAttribute <InjectAttribute>();
            //This resolves the binding
            IBinding binding = new InjectBinding(context.Parameter.ParameterType, injectAttribute.Name);

            return(Task.FromResult(binding));
        }
Ejemplo n.º 11
0
        private void ProcessMethodInfo(object mono, MethodInfo method, InjectAttribute inject = null)
        {
            if (inject == null)
            {
                inject = method.GetCustomAttributes(typeof(InjectAttribute), true).FirstOrDefault() as InjectAttribute;
            }

            injectAttributes.Add(inject);

            var parameters   = method.GetParameters();
            var paramObjects = Array.ConvertAll(parameters, p =>
            {
                Debug.Log("Para: " + p.Name + " " + p.ParameterType);
                return(container.ResolveObject(p.ParameterType, mono,
                                               inject == null ? LifeCycle.Default : inject.LifeCycle));
            });

            method.Invoke(mono, paramObjects);
        }
Ejemplo n.º 12
0
 /// <summary>
 /// Ensures that the real object exists, and creates it if it does not.
 /// </summary>
 internal void EnsureObject()
 {
     if (Real == null)
     {
         if (Manager.CurrentImpl == null)
         {
             throw new NotSupportedException("There are no interface implementations loaded");
         }
         Real = Manager.CurrentImpl.Ctor.Invoke(new object[0]);
         foreach (FieldInfo field in Real.GetType().GetTypeInfo().GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
         {
             InjectAttribute attr = field.GetCustomAttribute <InjectAttribute>();
             if (attr != null)
             {
                 field.SetValue(Real, Manager.Framework.GetSingleton(field.FieldType));
             }
         }
     }
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Try to resolve array of components, this should be used in other attribute process methods
        /// </summary>
        /// <param name="mono">object is expected as unity mono behaviour</param>
        /// <returns>true if you want to stop other attribute process methods</returns>
        private Component[] GetComponentsFromGameObject(object mono, Type type, InjectAttribute injectAttribute)
        {
            //not supported for transient or singleton injections
            if (injectAttribute.LifeCycle == LifeCycle.Transient ||
                injectAttribute.LifeCycle == LifeCycle.Singleton)
            {
                return(null);
            }

            var behaviour = mono as MonoBehaviour;

            if (behaviour == null)
            {
                return(null);
            }

            //output components
            Component[] components = null;

            //resolve by inject component to the gameobject
            var injectComponentArray = injectAttribute as IComponentArrayResolvable;

            if (injectComponentArray == null)
            {
                throw new InvalidOperationException(
                          "You must use apply injectAttribute with IComponentArrayResolvable to resolve array of components");
                //unable to get it from gameObject
            }

            components = injectComponentArray.GetComponents(behaviour, type.GetElementType());

            //unable to get it from gameObject
            if (components == null || components.Length == 0)
            {
                Debug.LogFormat("Unable to resolve components of {0} for {1}, found {2} elements",
                                type.GetElementType(), behaviour.name, components != null ? components.Length : 0);
            }

            return(components);
        }
Ejemplo n.º 14
0
        public object CreateObject(Type t)
        {
            mLogger?.Trace($"Attempt to create object of type '{t}'.");
            if (t.IsInterface)
            {
                throw new IncorrectContructorException(t,
                                                       "Type is interface. Registering only by type that is interface is not allowed.");
            }
            var           ctor              = t.GetConstructors().FirstOrDefault();
            var           ctorParams        = ctor.GetParameters();
            List <object> ctorParamsObjects = new List <object>();

            foreach (var parameterInfo in ctorParams)
            {
                InjectAttribute attr =
                    (InjectAttribute)Attribute.GetCustomAttributes(parameterInfo, typeof(InjectAttribute)).FirstOrDefault();
                if (parameterInfo.ParameterType == typeof(IoCContainer) ||
                    parameterInfo.ParameterType == typeof(InjectionProviderContract))
                {
                    ctorParamsObjects.Add(this);
                }
                else
                {
                    if (!parameterInfo.HasDefaultValue)
                    {
                        ctorParamsObjects.Add(attr != null ? Get <object>(attr.InjectingObjectName) : Get(parameterInfo.ParameterType));
                    }
                    else
                    {
                        ctorParamsObjects.Add(parameterInfo.DefaultValue);
                    }
                }
            }

            var result = ctor.Invoke(ctorParamsObjects.ToArray());

            mLogger?.Trace($"Object of type '{t}' created.");
            return(result);
        }
Ejemplo n.º 15
0
        private Property[] BuildProperties(PropertyInfo[] propsInfo)
        {
            List <Property> props = new List <Property>();

            if (propsInfo != null && propsInfo.Length > 0)
            {
                foreach (PropertyInfo item in propsInfo)
                {
                    InjectAttribute inj  = this.GetInjectAttribute(item);
                    Property        prop = new Property(item.Name);
                    if (!item.PropertyType.IsInterface && !item.PropertyType.IsClass)
                    {
                        prop.Set = inj.ValueToInject as string;
                    }
                    else
                    {
                        FillPropIfIsRefType(item, inj, prop);
                    }
                    props.Add(prop);
                }
            }
            return(props.ToArray());
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Try to resolve unity component, this should be used in other attribute process methods
        /// </summary>
        /// <param name="mono">object is expected as unity mono behaviour</param>
        /// <returns>true if you want to stop other attribute process methods</returns>
        private Component GetComponentFromGameObject(object mono, Type type, InjectAttribute injectAttribute)
        {
            //not supported for transient or singleton injections
            if (injectAttribute.LifeCycle == LifeCycle.Transient ||
                injectAttribute.LifeCycle == LifeCycle.Singleton)
            {
                return(null);
            }

            var behaviour = mono as MonoBehaviour;

            if (behaviour == null)
            {
                return(null);
            }

            //resolve by inject component to the gameobject
            var injectComponent = injectAttribute as IComponentResolvable;

            //output component
            Component component = null;

            //try get/add component with IInjectComponent interface
            if (injectComponent != null)
            {
                component = injectComponent.GetComponent(behaviour, type);

                //unable to get it from gameObject
                if (component == null)
                {
                    Debug.LogFormat("Unable to resolve component of {0} for {1}", type, behaviour.name);
                }
            }

            return(component);
        }
Ejemplo n.º 17
0
        protected InjectableElementBase(TProvider provider)
        {
            this.provider = provider;

            attribute = provider.GetAttribute <InjectAttribute>(true) ?? new InjectAttribute();
        }
Ejemplo n.º 18
0
 private static IMemberInjection CreateFieldInjection(IKernel kernel, FieldInfo f, InjectAttribute att)
 {
     return(new FieldInjection//字段注入元数据
     {
         Member = f,
         Reinjection = att != null ? att.Reinjection : true,
         Setter = f.ToMemberSetter(),//通过Emit的方式进行注入,
         Dependency = DependencyManager.Get(att != null ? att.Id : string.Empty, f.FieldType, kernel, false)
     });
 }
        public void CreateInstance_works()
        {
            var attribute = new InjectAttribute();

            Assert.IsType <InjectAttribute>(attribute);
        }
Ejemplo n.º 20
0
        private static IMemberInjection CreateMethodInjection(IComponentInfo ctx, IKernel kernel, MethodInfo m, InjectAttribute att)
        {
            var ps = m.GetParameters();
            List <IDependency> dependencyList = new List <IDependency>(ps.Length);

            foreach (var p in ps)
            {
                if (p.ParameterType.IsByRef || p.IsRetval || p.IsOut)
                {
                    return(null);
                }
                dependencyList.Add(AttributeProviderInspector.InspectParameter(ctx, kernel, p));
            }

            var id        = att != null ? att.Id : string.Empty;
            var injection = new MethodInjection(dependencyList.ToArray())//方法注入元数据
            {
                Member      = m,
                Method      = DynamicMethodFactory.GetProc(m),
                Reinjection = att.Reinjection,
            };

            return(injection);
        }
Ejemplo n.º 21
0
 private static IMemberInjection CreatePropertyInjection(IKernel kernel, PropertyInfo p, InjectAttribute att)
 {
     return(new PropertyInjection
     {
         Member = p,
         Reinjection = att != null ? att.Reinjection : true,
         Setter = p.ToMemberSetter(),
         Dependency = DependencyManager.Get(att != null ? att.Id : string.Empty, p.PropertyType, kernel, false)
     });
 }