Exemplo n.º 1
0
        public static void DependencyAttributeTests()
        {
            var attr1 = new DependencyAttribute("DependentAssembly", LoadHint.Always);

            Assert.Equal("DependentAssembly", attr1.DependentAssembly);
            Assert.Equal(LoadHint.Always, attr1.LoadHint);

            var attr2 = new DependencyAttribute(null, (LoadHint)(-2));

            Assert.Null(attr2.DependentAssembly);
            Assert.Equal((LoadHint)(-2), attr2.LoadHint);
        }
        public void ReturnsDependencyParameter()
        {
            DependencyAttribute attribute = new DependencyAttribute("Foo");

            attribute.NotPresentBehavior = NotPresentBehavior.Throw;

            IParameter result = attribute.CreateParameter(typeof(object));

            DependencyParameter parameter = AssertHelper.IsType <DependencyParameter>(result);

            Assert.AreEqual <object>("Foo", parameter.BuildKey);
            Assert.AreEqual(NotPresentBehavior.Throw, parameter.NotPresentBehavior);
        }
Exemplo n.º 3
0
        public void DependencyAttributeConstructor()
        {
            tlog.Debug(tag, $"DependencyAttributeConstructor START");

            var testingTarget = new DependencyAttribute(typeof(int));

            Assert.IsNotNull(testingTarget, "Can't create success object DependencyAttribute.");
            Assert.IsInstanceOf <DependencyAttribute>(testingTarget, "Should return DependencyAttribute instance.");

            Assert.IsNotNull(testingTarget.Implementor, "Should not be null");

            tlog.Debug(tag, $"DependencyAttributeConstructor END");
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="il"></param>
        /// <param name="paramAttr"></param>
        /// <param name="parameterType"></param>
        public override void EmitParameterResolution(ILGenerator il, ParameterAttribute paramAttr, Type parameterType)
        {
            DependencyAttribute attr = (DependencyAttribute)paramAttr;

            ConstructorInfo dependencyResolverCtor =
                GetConstructor <DependencyResolver>(typeof(IBuilderContext));

            MethodInfo resolve = GetMethodInfo <DependencyResolver>("Resolve",
                                                                    typeof(Type), typeof(Type), typeof(string),
                                                                    typeof(NotPresentBehavior), typeof(SearchMode));

            // Create the dependency resolver object
            // Constructor takes context
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Newobj, dependencyResolverCtor);

            // Call frame for call to .Resolve

            // Actual parameter type
            EmitLoadType(il, parameterType);

            // Type to create
            if (attr.CreateType != null)
            {
                EmitLoadType(il, attr.CreateType);
            }
            else
            {
                il.Emit(OpCodes.Ldnull);
            }

            // id
            if (attr.Name != null)
            {
                il.Emit(OpCodes.Ldstr, attr.Name);
            }
            else
            {
                il.Emit(OpCodes.Ldnull);
            }

            // NotPresentBehavior
            il.Emit(OpCodes.Ldc_I4, (int)attr.NotPresentBehavior);

            // SearchMode
            il.Emit(OpCodes.Ldc_I4, (int)attr.SearchMode);

            // And call it
            il.EmitCall(OpCodes.Call, resolve, null);
        }
        public static void InitializeDependencies(this IMobileObject obj)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("Injection of dependencies cannot be performed in a 'null' instance.");
            }

            IBusinessScope scopedObject = obj as IBusinessScope;

            if (scopedObject != null)
            {
                if (scopedObject.Scope == null)
                {
                    throw new ArgumentNullException("obj", "An instance of IMobileObject that also implements IBusinessScope needs to have the Scope set before you can call InitializeDependencies on it!");
                }

                scopedObject.ReflectProperties(DPABindingFlags)
                .Where(pi => Attribute.IsDefined(pi, typeof(DependencyAttribute)))
                .ToList <PropertyInfo>()
                .ForEach(pi =>
                {
                    DependencyAttribute atb = pi.GetCustomAttribute <DependencyAttribute>();

                    if (scopedObject.Scope.IsRegistered(pi.PropertyType))
                    {
                        object depPropInstance = scopedObject.Scope.Resolve(pi.PropertyType);

                        if ((atb.DependencyScope == ResolutionScope.Client || atb.DependencyScope == ResolutionScope.ClientAndServer) && typeof(IDisposable).IsAssignableFrom(depPropInstance.GetType()))
                        {
                            IComponentRegistration reg = scopedObject.Scope
                                                         .ComponentRegistry
                                                         .RegistrationsFor(new TypedService(pi.PropertyType))
                                                         .Where(e => e.Ownership == InstanceOwnership.ExternallyOwned).FirstOrDefault();
                            if (reg == null)
                            {
                                throw new ConcreteTypeResolutionException(obj.GetType(), "Did not find a registration for given type.");
                            }
                        }

                        pi.SetValue(obj, depPropInstance);
                    }
                });
            }
        }
        /// <summary>
        /// 检查 <paramref name="type"/> 类公共可写属性上的
        /// <see cref="DependencyAttribute"/> 标注.
        /// 如果找到, 则向容器注册此属性要求依赖注入.
        /// </summary>
        /// <param name="type"></param>
        private void LoadDependencyAttributes(Type type)
        {
            foreach (PropertyInfo prop in type.GetProperties(
                         BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance))
            {
                if (prop.GetIndexParameters().Length == 0 &&
                    prop.CanWrite &&
                    prop.IsDefined(typeof(DependencyAttribute), false))
                {
                    DependencyAttribute dep =
                        (DependencyAttribute)Attribute.GetCustomAttribute(
                            prop, typeof(DependencyAttribute), false);

                    _container.RegisterType(type,
                                            new InjectionProperty(prop.Name,
                                                                  new ResolvedParameter(prop.PropertyType, dep.ResolveName)));
                }
            }
        }
Exemplo n.º 7
0
        /// <summary>属性注入</summary>
        /// <param name="cls"></param>
        private void DIAttr(BindData bindData, object cls)
        {
            if (cls == null)
            {
                return;
            }

            string typeName;

            foreach (PropertyInfo property in cls.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (!property.CanWrite)
                {
                    continue;
                }
                object[] propertyAttrs = property.GetCustomAttributes(typeof(DependencyAttribute), true);
                if (propertyAttrs.Length <= 0)
                {
                    continue;
                }

                DependencyAttribute dependency = propertyAttrs[0] as DependencyAttribute;
                if (string.IsNullOrEmpty(dependency.Alias))
                {
                    typeName = property.PropertyType.ToString();
                }
                else
                {
                    typeName = dependency.Alias;
                }

                if (property.PropertyType.IsClass || property.PropertyType.IsInterface)
                {
                    property.SetValue(cls, ResloveClassAttr(bindData, cls.GetType(), typeName), null);
                }
                else
                {
                    property.SetValue(cls, ResolveNonClassAttr(bindData, cls.GetType(), typeName), null);
                }
            }
        }
        /// <summary>
        /// InjectionConstructor 和 InjectionMethod 公用的参数列表分析过程
        /// </summary>
        /// <param name="method"></param>
        /// <returns></returns>
        private List <object> BuildMethodParametersInfoList(MethodBase method)
        {
            List <object> paramList = new List <object>();

            foreach (ParameterInfo parameter in method.GetParameters())
            {
                if (parameter.IsDefined(typeof(DependencyAttribute), false))
                {
                    DependencyAttribute dep = (DependencyAttribute)
                                              Attribute.GetCustomAttribute(
                        parameter, typeof(DependencyAttribute));
                    ResolvedParameter p =
                        new ResolvedParameter(parameter.ParameterType, dep.ResolveName);
                    paramList.Add(p);
                }
                else
                {
                    paramList.Add(parameter.ParameterType);
                }
            }
            return(paramList);
        }
        //disposes the scoped objects ILifetimeScope and sets all dependency properties to null
        public static void FinalizeDependencies(this IMobileObject obj)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("Object to be processed for dependency injection cannot be 'null'.");
            }

            IBusinessScope scopedObject = obj as IBusinessScope;

            if (scopedObject != null)
            {
                if (scopedObject.Scope != null)
                {
                    //if the scope is disposed the dependency that was resolved from it will get disposed as well -
                    //we need to ensure that the dependencies we bring back from the client do NOT implememnt IDisposable
                    //OR - if they do - we need to ensure that the container was registered to not track the client dependency
                    //(this happens in the
                    scopedObject.Scope.Dispose();
                    scopedObject.Scope = null;

                    scopedObject.ReflectProperties(DPABindingFlags)
                    .Where(pi => Attribute.IsDefined(pi, typeof(DependencyAttribute)))
                    .ToList <PropertyInfo>()
                    .ForEach(pi =>
                    {
                        DependencyAttribute atb = pi.GetCustomAttribute <DependencyAttribute>();
                        //we only clear out the scoped object if it is only used on the server side
                        //we checked for IDisposable and made sure that the client side dependency was not being tracked by
                        //the server side resolution in Autofac when InitializeObject was called so we will be okay to not clear it out
                        //and do not need to worry about it getting disposed here as well
                        if (atb.DependencyScope == ResolutionScope.Server)
                        {
                            pi.SetValue(scopedObject, null);
                        }
                    });
                }
            }
        }
 public ScheduledDependencyInjection(string name, DependencyAttribute attribute, Action <PluginBase> injection)
 {
     Name   = name;
     Info   = attribute;
     Inject = injection;
 }
 static ServiceLifetime?GetLifeTimeOrNull(Type type, DependencyAttribute dependencyAttribute)
 {
     return(dependencyAttribute?.Lifetime ?? GetServiceLifetimeFromClassHierarcy(type));
 }
Exemplo n.º 12
0
 protected virtual ServiceLifetime?GetLifeTimeOrNull(Type type, [CanBeNull] DependencyAttribute dependencyAttribute)
 {
     return(dependencyAttribute?.Lifetime ?? GetServiceLifetimeFromClassHierarchy(type) ?? GetDefaultLifeTimeOrNull(type));
 }
 protected virtual ServiceLifetime?GetLifeTimeOrNull(Type type, DependencyAttribute dependencyAttribute)
 {
     return(dependencyAttribute.Lifetime ?? GetServiceLifetimeFromCLassHierarcy(type));
 }
Exemplo n.º 14
0
 public static string GetTaskName(DependencyAttribute attribute)
 {
     return(GetTaskName(attribute.Task));
 }
Exemplo n.º 15
0
 private static Dependency CreateDependency(Type @class, DependencyAttribute attr)
 {
     return(new Dependency(@class, attr.Supplier, attr.Name));
 }