/// <summary>
        /// Return the sequence of methods to call while building the target object.
        /// </summary>
        /// <param name="context">Current build context.</param>
        /// <param name="resolverPolicyDestination">The <see cref='IPolicyList'/> to add any
        /// generated resolver objects into.</param>
        /// <returns>Sequence of methods to call.</returns>
        public IEnumerable <SelectedMethod> SelectMethods(IBuilderContext context, IPolicyList resolverPolicyDestination)
        {
            foreach (Tuple <MethodInfo, IEnumerable <InjectionParameterValue> > method in _methods)
            {
                Type           typeToBuild = context.BuildKey.Type;
                SelectedMethod selectedMethod;
                var            info = method.Item1.DeclaringType.GetTypeInfo();
                var            methodHasOpenGenericParameters = method.Item1.GetParameters()
                                                                .Select(p => p.ParameterType.GetTypeInfo())
                                                                .Any(i => i.IsGenericType && i.ContainsGenericParameters);
                if (!methodHasOpenGenericParameters && !(info.IsGenericType && info.ContainsGenericParameters))
                {
                    selectedMethod = new SelectedMethod(method.Item1);
                }
                else
                {
                    var closedMethodParameterTypes = method.Item1
                                                     .GetClosedParameterTypes(typeToBuild.GetTypeInfo().GenericTypeArguments);

                    selectedMethod = new SelectedMethod(typeToBuild.GetMethodsHierarchical()
                                                        .Single(m => m.Name.Equals(method.Item1.Name) &&
                                                                m.GetParameters().ParametersMatch(closedMethodParameterTypes)));
                }

                AddParameterResolvers(typeToBuild, resolverPolicyDestination,
                                      method.Item2, selectedMethod);

                yield return(selectedMethod);
            }
        }
        /// <summary>
        /// Choose the constructor to call for the given type.
        /// </summary>
        /// <param name="context">Current build context</param>
        /// <param name="resolverPolicyDestination">The <see cref='IPolicyList'/> to add any
        /// generated resolver objects into.</param>
        /// <returns>The chosen constructor.</returns>
        public SelectedConstructor SelectConstructor(IBuilderContext context, IPolicyList resolverPolicyDestination)
        {
            SelectedConstructor result;

            var typeInfo = (context ?? throw new ArgumentNullException(nameof(context))).BuildKey
                           .Type
                           .GetTypeInfo();
            var methodHasOpenGenericParameters = _ctor.GetParameters()
                                                 .Select(p => p.ParameterType.GetTypeInfo())
                                                 .Any(i => i.IsGenericType && i.ContainsGenericParameters);

            var ctorTypeInfo = _ctor.DeclaringType.GetTypeInfo();

            if (!methodHasOpenGenericParameters && !(ctorTypeInfo.IsGenericType && ctorTypeInfo.ContainsGenericParameters))
            {
                result = new SelectedConstructor(_ctor);
            }
            else
            {
                var closedCtorParameterTypes = _ctor.GetClosedParameterTypes(typeInfo.GenericTypeArguments);

                var constructor = typeInfo.DeclaredConstructors
                                  .Single(c => !c.IsStatic && c.GetParameters().ParametersMatch(closedCtorParameterTypes));

                result = new SelectedConstructor(constructor);
            }

            foreach (var parameterValue in _parameterValues)
            {
                var resolver = parameterValue.GetResolverPolicy(context.BuildKey.Type);
                result.AddParameterResolver(resolver);
            }

            return(result);
        }
        /// <summary>
        /// Sets a generic individual policy.
        /// </summary>
        /// <typeparam name="TPolicyInterface">The interface the policy is registered under.</typeparam>
        /// <param name="policies"><see cref="IPolicyList"/> to add the policy to.</param>
        /// <param name="policy">The policy to be registered.</param>
        /// <param name="buildKey">The key the policy applies.</param>
        public static void Set <TPolicyInterface>(this IPolicyList policies, TPolicyInterface policy, object buildKey)
            where TPolicyInterface : IBuilderPolicy
        {
            var key = ParseBuildKey(buildKey);

            (policies ?? throw new ArgumentNullException(nameof(policies))).Set(key.Item1, key.Item2, typeof(TPolicyInterface), policy);
        }
        void IContainerPolicyCreator.CreatePolicies(
            IPolicyList policyList,
            string instanceName,
            ConfigurationElement configurationObject,
            IConfigurationSource configurationSource)
        {
            CacheManagerData castConfigurationObject = (CacheManagerData)configurationObject;
            var cacheManagerName = instanceName;
            var cacheStorageName = castConfigurationObject.CacheStorage;
            var maximumElementsInCacheBeforeScavenging = castConfigurationObject.MaximumElementsInCacheBeforeScavenging;
            var numberToRemoveWhenScavenging           = castConfigurationObject.NumberToRemoveWhenScavenging;
            var expirationPollFrequencyInSeconds       = castConfigurationObject.ExpirationPollFrequencyInSeconds;

            policyList.Set <IBuildPlanPolicy>(
                new DelegateBuildPlanPolicy(
                    context =>
            {
                IBuilderContext backingStoreContext
                    = context.CloneForNewBuild(NamedTypeBuildKey.Make <IBackingStore>(cacheStorageName), null);
                IBackingStore backingStore = (IBackingStore)context.Strategies.ExecuteBuildUp(backingStoreContext);
                CachingInstrumentationProvider instrumentationProvider
                    = CreateInstrumentationProvider(cacheManagerName, configurationSource);
                return(new CacheManagerFactoryHelper().BuildCacheManager(
                           cacheManagerName,
                           backingStore,
                           maximumElementsInCacheBeforeScavenging,
                           numberToRemoveWhenScavenging,
                           expirationPollFrequencyInSeconds,
                           instrumentationProvider));
            }),
                NamedTypeBuildKey.Make <CacheManager>(cacheManagerName));
        }
 /// <summary>
 /// Add policies to the <paramref name="policies"/> to configure the
 /// container to call this constructor with the appropriate parameter values.
 /// </summary>
 /// <param name="typeToCreate">Type to register.</param>
 /// <param name="name">Name used to resolve the type object.</param>
 /// <param name="policies">Policy list to add policies to.</param>
 public override void AddPolicies(Type typeToCreate, string name, IPolicyList policies)
 {
     ConstructorInfo ctor = FindConstructor(typeToCreate);
     policies.Set<IConstructorSelectorPolicy>(
         new SpecifiedConstructorSelectorPolicy(ctor, parameterValues.ToArray()),
         new NamedTypeBuildKey(typeToCreate, name));
 }
        public IEnumerable<SelectedProperty> SelectProperties(IBuilderContext context, IPolicyList resolverPolicyDestination)
        {
            var t = context.BuildKey.Type;
             var propertyNames = new HashSet<string>();
             foreach (SelectedProperty prop in specifiedPropertiesPolicy.SelectProperties(context,resolverPolicyDestination))
             {
            if (!propertyNames.Contains(prop.Property.Name))
            {
               propertyNames.Add(prop.Property.Name);
               yield return prop;
            }
             }
             foreach (SelectedProperty prop in defaultProlicy.SelectProperties(context,resolverPolicyDestination))
             {
            if (!propertyNames.Contains(prop.Property.Name))
            {
               yield return prop;
            }
             }

             foreach (PropertyInfo prop in t.GetProperties(BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance))
             {
            if (prop.GetIndexParameters().Length == 0 &&
               prop.CanWrite && !ShoudBeIgnored(prop) &&
               !propertyNames.Contains(prop.Name) &&
               !prop.PropertyType.IsValueType &&
               CanBeResolved(prop))
            {
               yield return CreateSelectedProperty(context, prop);
            }
             }
        }
Example #7
0
 internal ContainerRegistration(Type registeredType, string name, IPolicyList policies)
 {
     this.buildKey = new NamedTypeBuildKey(registeredType, name);
     MappedToType = GetMappedType(policies);
     LifetimeManagerType = GetLifetimeManagerType(policies);
     LifetimeManager = GetLifetimeManager(policies);
 }
Example #8
0
        /// <summary>
        /// Choose the constructor to call for the given type.
        /// </summary>
        /// <param name="context">Current build context</param>
        /// <param name="resolverPolicyDestination">The <see cref='IPolicyList'/> to add any
        /// generated resolver objects into.</param>
        /// <returns>The chosen constructor.</returns>
        public SelectedConstructor SelectConstructor(IBuilderContext context, IPolicyList resolverPolicyDestination)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            var typeToConstruct     = context.BuildKey.Type;
            var constructors        = typeToConstruct.GetConstructors();
            var selectedConstructor =
                SelectConstructor(constructors.Where(ctor => ctor.IsDefined(typeof(InjectionAttribute), true)).ToArray()) ??
                SelectConstructor(constructors.Where(ctor => ctor.IsDefined(typeof(InjectionConstructorAttribute), true)).ToArray()) ??
                SelectConstructor(constructors);

            if (selectedConstructor != null)
            {
                var result = new SelectedConstructor(selectedConstructor);
                foreach (var parameter in selectedConstructor.GetParameters())
                {
                    var attrs = parameter.GetCustomAttributes <DependencyResolutionAttribute>(false).ToArray();
                    if (attrs.Length > 0)
                    {
                        // Since this attribute is defined with MultipleUse = false, the compiler will
                        // enforce at most one. So we don't need to check for more.
                        result.AddParameterResolver(attrs[0].CreateResolver(parameter.ParameterType));
                    }
                    else
                    {
                        // No attribute, just go back to the container for the default for that type.
                        result.AddParameterResolver(new NamedTypeDependencyResolverPolicy(parameter.ParameterType, null));
                    }
                }
                return(result);
            }
            return(null);
        }
 /// <summary>
 ///   Return the sequence of methods to call while building the target object.
 /// </summary>
 /// <param name = "context">Current build context.</param>
 /// <param name = "resolverPolicyDestination">The <see cref = 'IPolicyList' /> to add any
 ///   generated resolver objects into.</param>
 /// <returns>Sequence of methods to call.</returns>
 public IEnumerable<SelectedMethod> SelectMethods(IBuilderContext context, IPolicyList resolverPolicyDestination)
 {
     foreach (Pair<MethodInfo, IEnumerable<InjectionParameterValue>> method in methods)
     {
         Type typeToBuild = context.BuildKey.Type;
         SelectedMethod selectedMethod;
         var typeReflector = new ReflectionHelper(method.First.DeclaringType);
         var methodReflector = new MethodReflectionHelper(method.First);
         if (!methodReflector.MethodHasOpenGenericParameters && !typeReflector.IsOpenGeneric)
         {
             selectedMethod = new SelectedMethod(method.First);
         }
         else
         {
             Type[] closedMethodParameterTypes =
                 methodReflector.GetClosedParameterTypes(typeToBuild.GetGenericArguments());
             selectedMethod = new SelectedMethod(
                 typeToBuild.GetMethod(method.First.Name, closedMethodParameterTypes));
         }
         SpecifiedMemberSelectorHelper.AddParameterResolvers(
             typeToBuild,
             resolverPolicyDestination,
             method.Second,
             selectedMethod);
         yield return selectedMethod;
     }
 }
Example #10
0
        private static IBuilderPolicy GetExtended(IPolicyList list, Type policyInterface, INamedType buildKey, Type buildType, out IPolicyList containingPolicyList)
        {
            containingPolicyList = null;
            if (null == buildType)
            {
                return(null);
            }

            // Check if generic
            if (buildType.GetTypeInfo().IsGenericType)
            {
                var newType = buildType.GetGenericTypeDefinition();
                return(list.Get(newType, buildKey.Name, policyInterface, out containingPolicyList) ??
                       list.Get(newType, string.Empty, policyInterface, out containingPolicyList));
            }

            // Check if array
            if (buildType.IsArray && buildType.GetArrayRank() == 1)
            {
                return(list.Get(typeof(Array), buildKey.Name, policyInterface, out containingPolicyList) ??
                       list.Get(typeof(Array), string.Empty, policyInterface, out containingPolicyList));
            }

            // Check default for type
            return(list.Get(buildType, string.Empty, policyInterface, out containingPolicyList));
        }
Example #11
0
            public SelectedConstructor SelectConstructor(IBuilderContext context, IPolicyList resolverPolicyDestination)
            {
                var originalConstructor = _originalConstructorSelectorPolicy.SelectConstructor(context, resolverPolicyDestination);

                if (originalConstructor.Constructor.GetParameters().All(arg => _container.CanResolve(arg.ParameterType)))
                {
                    return(originalConstructor);
                }
                else
                {
                    var newSelectedConstructor = FindNewCtor(originalConstructor);
                    if (newSelectedConstructor == null)
                    {
                        return(originalConstructor);
                    }

                    foreach (var newParameterResolver in
                             originalConstructor.GetParameterResolvers().Take(newSelectedConstructor.Constructor.GetParameters().Length))
                    {
                        newSelectedConstructor.AddParameterResolver(newParameterResolver);
                    }

                    return(newSelectedConstructor);
                }
            }
Example #12
0
        void IContainerPolicyCreator.CreatePolicies(
            IPolicyList policyList,
            string instanceName,
            ConfigurationElement configurationObject,
            IConfigurationSource configurationSource)
        {
            T castConfigurationObject = (T)configurationObject;
            ConstructorInfo ctor      = castConfigurationObject.Type.GetConstructor(
                BindingFlags.Public | BindingFlags.Instance, null, constructorTypes, null);

            if (ctor == null)
            {
                throw new ArgumentException(
                          string.Format(
                              CultureInfo.CurrentCulture,
                              Resources.ExceptionCustomProviderTypeDoesNotHaveTheRequiredConstructor,
                              castConfigurationObject.Type.AssemblyQualifiedName),
                          "configurationObject");
            }
            SelectedConstructor selectedCtor = new SelectedConstructor(ctor);
            string parameterKey = Guid.NewGuid().ToString();

            selectedCtor.AddParameterKey(parameterKey);
            policyList.Set <IConstructorSelectorPolicy>(
                new FixedConstructorSelectorPolicy(selectedCtor),
                new NamedTypeBuildKey(castConfigurationObject.Type, instanceName));
            policyList.Set <IDependencyResolverPolicy>(
                new ConstantResolverPolicy(new NameValueCollection(castConfigurationObject.Attributes)),
                parameterKey);
        }
Example #13
0
        public static TPolicyInterface Get <TPolicyInterface>(this IPolicyList policies, object buildKey, out IPolicyList containingPolicyList)
            where TPolicyInterface : IBuilderPolicy
        {
            Guard.ArgumentNotNull(policies, "policies");

            return((TPolicyInterface)policies.Get(typeof(TPolicyInterface), buildKey, false, out containingPolicyList));
        }
        void IContainerPolicyCreator.CreatePolicies(
            IPolicyList policyList,
            string instanceName,
            ConfigurationElement configurationObject,
            IConfigurationSource configurationSource)
        {
            ConnectionStringSettings castConfigurationObject = (ConnectionStringSettings)configurationObject;
            IList <IOraclePackage>   packages = new IOraclePackage[0];
            OracleConnectionSettings oracleConnectionSettings = OracleConnectionSettings.GetSettings(configurationSource);

            if (oracleConnectionSettings != null)
            {
                OracleConnectionData oracleConnectionData
                    = oracleConnectionSettings.OracleConnectionsData.Get(castConfigurationObject.Name);
                if (oracleConnectionData != null)
                {
                    packages = new List <IOraclePackage>(from op in oracleConnectionData.Packages select(IOraclePackage) op);
                }
            }
            new PolicyBuilder <OracleDatabase, ConnectionStringSettings>(
                instanceName,
                castConfigurationObject,
                c => new OracleDatabase(c.ConnectionString, packages))
            .AddPoliciesToPolicyList(policyList);
        }
Example #15
0
 /// <summary>
 /// Add policies to the <paramref name="policies"/> to configure the
 /// container to call this constructor with the appropriate parameter values.
 /// </summary>
 /// <param name="serviceType">Interface registered, ignored in this implementation.</param>
 /// <param name="implementationType">Type to register.</param>
 /// <param name="name">Name used to resolve the type object.</param>
 /// <param name="policies">Policy list to add policies to.</param>
 public override void AddPolicies(Type serviceType, Type implementationType, string name, IPolicyList policies)
 {
     ConstructorInfo ctor = this.FindConstructor(implementationType);
     policies.Set<IConstructorSelectorPolicy>(
         new SpecifiedConstructorSelectorPolicy(ctor, this.parameterValues.ToArray()),
         new NamedTypeBuildKey(implementationType, name));
 }
Example #16
0
        public void InjectionConstructorSetsResolverForInterfaceToLookupInContainer()
        {
            InjectionConstructor  ctor    = new InjectionConstructor("Logger", typeof(ILogger));
            TestingBuilderContext context = new TestingBuilderContext();

            context.BuildKey = typeof(GuineaPig);
            IPolicyList policies = context.PersistentPolicies;

            ctor.AddPolicies(typeof(GuineaPig), policies);

            IConstructorSelectorPolicy selector = policies.Get <IConstructorSelectorPolicy>(
                new NamedTypeBuildKey(typeof(GuineaPig)));

            SelectedConstructor selected = selector.SelectConstructor(context);

            string[] keys = selected.GetParameterKeys();

            Assert.AreEqual(typeof(GuineaPig).GetConstructor(Sequence.Collect(typeof(string), typeof(ILogger))), selected.Constructor);
            Assert.AreEqual(2, keys.Length);

            IDependencyResolverPolicy policy =
                context.Policies.Get <IDependencyResolverPolicy>(keys[1]);

            Assert.IsTrue(policy is NamedTypeDependencyResolverPolicy);
        }
Example #17
0
        void IContainerPolicyCreator.CreatePolicies(
            IPolicyList policyList,
            string instanceName,
            ConfigurationElement configurationObject,
            IConfigurationSource configurationSource)
        {
            IEnumerable <ConstructorInfo> ctors
                = from ctor in this.targetType.GetConstructors(BindingFlags.Public | BindingFlags.Instance)
                  orderby ctor.GetParameters().Length descending
                  select ctor;

            foreach (ConstructorInfo ctor in ctors)
            {
                if (TryToMatchAndAddPolicies(ctor, configurationObject, policyList, instanceName))
                {
                    return;
                }
            }
            throw new ArgumentException(
                      string.Format(
                          CultureInfo.CurrentCulture,
                          Resources.ExceptionUnableToMatchConstructorToConfigurationObject,
                          configurationObject.GetType().AssemblyQualifiedName,
                          this.targetType.AssemblyQualifiedName));
        }
Example #18
0
        private ILifetimePolicy GetLifetimePolicy(IBuilderContext context, out IPolicyList source)
        {
            var policy = context.Policies.Get(context.OriginalBuildKey.Type, context.OriginalBuildKey.Name, typeof(ILifetimePolicy), out source);

            if (policy == null && context.OriginalBuildKey.Type.GetTypeInfo().IsGenericType)
            {
                policy = context.Policies.Get(context.BuildKey.Type.GetGenericTypeDefinition(), context.BuildKey.Name, typeof(ILifetimePolicy), out source);
                if (!(policy is ILifetimeFactoryPolicy factoryPolicy))
                {
                    return(null);
                }

                lock (_genericLifetimeManagerLock)
                {
                    // check whether the policy for closed-generic has been added since first checked
                    var newLifetime = (ILifetimePolicy)source.Get(context.OriginalBuildKey.Type, context.OriginalBuildKey.Name, typeof(ILifetimePolicy), out _);
                    if (null == newLifetime)
                    {
                        newLifetime = factoryPolicy.CreateLifetimePolicy();
                        source.Set(context.OriginalBuildKey.Type, context.OriginalBuildKey.Name, typeof(ILifetimePolicy), newLifetime);
                        if (newLifetime is IDisposable)
                        {
                            context.Lifetime.Add(newLifetime);
                        }
                    }

                    return(newLifetime);
                }
            }

            return((ILifetimePolicy)policy);
        }
Example #19
0
        /// <summary>
        /// Return the sequence of methods to call while building the target object.
        /// </summary>
        /// <param name="context">Current build context.</param>
        /// <param name="resolverPolicyDestination">The <see cref='IPolicyList'/> to add any
        /// generated resolver objects into.</param>
        /// <returns>Sequence of methods to call.</returns>
        public IEnumerable <SelectedMethod> SelectMethods(IBuilderContext context, IPolicyList resolverPolicyDestination)
        {
            foreach (Pair <MethodInfo, IEnumerable <InjectionParameterValue> > method in methods)
            {
                Type                   typeToBuild = context.BuildKey.Type;
                SelectedMethod         selectedMethod;
                ReflectionHelper       typeReflector   = new ReflectionHelper(method.First.DeclaringType);
                MethodReflectionHelper methodReflector = new MethodReflectionHelper(method.First);
                if (!methodReflector.MethodHasOpenGenericParameters && !typeReflector.IsOpenGeneric)
                {
                    selectedMethod = new SelectedMethod(method.First);
                }
                else
                {
                    Type[] closedMethodParameterTypes =
                        methodReflector.GetClosedParameterTypes(typeToBuild.GetTypeInfo().GenericTypeArguments);
                    selectedMethod = new SelectedMethod(
                        typeToBuild.GetMethodHierarchical(method.First.Name, closedMethodParameterTypes));
                }

                SpecifiedMemberSelectorHelper.AddParameterResolvers(
                    typeToBuild,
                    resolverPolicyDestination,
                    method.Second,
                    selectedMethod);
                yield return(selectedMethod);
            }
        }
Example #20
0
        public void InjectionConstructorInsertsChooserForConstructorWithParameters()
        {
            string expectedString = "Hello";
            int    expectedInt    = 12;

            var ctor    = new InjectionConstructor(expectedString, expectedInt);
            var context = new MockBuilderContext
            {
                BuildKey = new NamedTypeBuildKey(typeof(GuineaPig))
            };
            IPolicyList policies = context.PersistentPolicies;

            ctor.AddPolicies(typeof(GuineaPig), policies);

            var selector = policies.Get <IConstructorSelectorPolicy>(
                new NamedTypeBuildKey(typeof(GuineaPig)));

            SelectedConstructor selected = selector.SelectConstructor(context, policies);

            string[] keys = selected.GetParameterKeys();

            Assert.AreEqual(typeof(GuineaPig).GetConstructor(Sequence.Collect(typeof(string), typeof(int))), selected.Constructor);
            Assert.AreEqual(2, keys.Length);

            Assert.AreEqual(expectedString, (string)ResolveValue(policies, keys[0]));
            Assert.AreEqual(expectedInt, (int)ResolveValue(policies, keys[1]));
        }
Example #21
0
            public SelectedConstructor SelectConstructor(IBuilderContext context, IPolicyList resolverPolicyDestination)
            {
                SelectedConstructor originalConstructor =
                    originalConstructorSelectorPolicy.SelectConstructor(context, resolverPolicyDestination);

                return(FindNewConstructor(originalConstructor, interceptingType));
            }
Example #22
0
        /// <summary>
        /// Finish the creation process by adding all the collected policies to <paramref name="policyList"/>.
        /// </summary>
        /// <param name="policyList">The destination <see cref="IPolicyList"/>.</param>
        public void AddPoliciesToPolicyList(IPolicyList policyList)
        {
            CheckFinished();

            if (this.propertyWaitCount > 0)
            {
                throw new InvalidOperationException(Resources.ExceptionPolicyBuilderStillWaitingForPropertyPolicy);
            }

            this.finished = true;

            if (this.selectedConstructor != null)
            {
                policyList.Set <IConstructorSelectorPolicy>(
                    new FixedConstructorSelectorPolicy(this.selectedConstructor),
                    this.instanceKey);
            }

            if (this.selectedProperties.Count > 0)
            {
                policyList.Set <IPropertySelectorPolicy>(
                    new FixedPropertySelectorPolicy(this.selectedProperties),
                    this.instanceKey);
            }

            foreach (var item in this.resolverPolicies)
            {
                policyList.Set(item.Value, item.Key);
            }
        }
Example #23
0
 private static void CreateCacheManagerLifetimePolicies(IPolicyList policyList, IUnityContainer container, IEnumerable <CacheManagerDataBase> cacheManagers)
 {
     foreach (var cacheManagerData in cacheManagers)
     {
         container.RegisterType(cacheManagerData.Type, cacheManagerData.Name, new ContainerControlledLifetimeManager());
     }
 }
Example #24
0
 internal ContainerRegistration(Type registeredType, string name, IPolicyList policies)
 {
     this.buildKey       = new NamedTypeBuildKey(registeredType, name);
     MappedToType        = GetMappedType(policies);
     LifetimeManagerType = GetLifetimeManagerType(policies);
     LifetimeManager     = GetLifetimeManager(policies);
 }
Example #25
0
        public object Resolve(Type type, string name, ImplicitRegistration registration)
        {
            unsafe
            {
                var thisContext = this;
                var context     = new BuilderContext
                {
                    Lifetime         = Lifetime,
                    Registration     = registration,
                    RegistrationType = type,
                    Name             = name,
                    Type             = registration is ExplicitRegistration containerRegistration ? containerRegistration.Type : type,
                    ExecutePlan      = ExecutePlan,
                    ResolvePlan      = ResolvePlan,
                    List             = List,
                    Overrides        = Overrides,
                    DeclaringType    = Type,
#if !NET40
                    Parent = new IntPtr(Unsafe.AsPointer(ref thisContext))
#endif
                };

                return(ExecutePlan(registration.BuildChain, ref context));
            }
        }
Example #26
0
        public static void SetDefault <TPolicyInterface>(this IPolicyList policies, TPolicyInterface policy)
            where TPolicyInterface : IBuilderPolicy
        {
            ClubCloud.Core.Unity.Utility.Guard.ArgumentNotNull(policies, "policies");

            policies.SetDefault(typeof(TPolicyInterface), policy);
        }
Example #27
0
        /// <summary>
        /// Get the non default policy.
        /// </summary>
        /// <param name="policies"><see cref="IPolicyList"/> to search.</param>
        /// <param name="policyInterface">The interface the policy is registered under.</param>
        /// <param name="buildKey">The key the policy applies.</param>
        /// <param name="localOnly">true if the policy searches local only; otherwise false to seach up the parent chain.</param>
        /// <returns>The policy in the list, if present; returns null otherwise.</returns>
        public static IBuilderPolicy GetNoDefault(this IPolicyList policies, Type policyInterface,
                                                  object buildKey,
                                                  bool localOnly)
        {
            IPolicyList containingPolicyList;

            return(policies.GetNoDefault(policyInterface, buildKey, localOnly, out containingPolicyList));
        }
 public void CreatePolicies(
     IPolicyList policyList,
     string instanceName,
     ConfigurationElement configurationObject,
     IConfigurationSource configurationSource)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Add policies to the <paramref name="policies"/> to configure the
        /// container to call this constructor with the appropriate parameter values.
        /// </summary>
        /// <param name="typeToCreate">Type to register.</param>
        /// <param name="name">Name used to resolve the type object.</param>
        /// <param name="policies">Policy list to add policies to.</param>
        public override void AddPolicies(Type typeToCreate, string name, IPolicyList policies)
        {
            ConstructorInfo ctor = FindConstructor(typeToCreate);

            policies.Set <IConstructorSelectorPolicy>(
                new SpecifiedConstructorSelectorPolicy(ctor, parameterValues.ToArray()),
                new NamedTypeBuildKey(typeToCreate, name));
        }
Example #30
0
 /// <summary>
 /// Remove the currently tracked resolvers from the given policy list.
 /// </summary>
 /// <param name="policies">Policy list to remove the resolvers from.</param>
 public void RemoveResolvers(IPolicyList policies)
 {
     foreach (object key in keys)
     {
         policies.Clear <IDependencyResolverPolicy>(key);
     }
     keys.Clear();
 }
        /// <summary>
        /// Add policies to the <paramref name="policies"/> to configure the container with 
        /// an appropriate <see cref="IInstanceInterceptionPolicy"/>
        /// </summary>
        /// <param name="serviceType">Type of the interface being registered. This parameter is
        /// ignored by this class.</param>
        /// <param name="implementationType">Type to register.</param>
        /// <param name="name">Name used to resolve the type object.</param>
        /// <param name="policies">Policy list to add policies to.</param>
        public override void AddPolicies(Type serviceType, Type implementationType, string name, IPolicyList policies)
        {
            var key = new NamedTypeBuildKey(implementationType);
            policies.Set<IInstanceInterceptionPolicy>(new FixedInstanceInterceptionPolicy(Interceptor), key);

            var piabInjectionMember = new InterceptionBehavior<PolicyInjectionBehavior>();
            piabInjectionMember.AddPolicies(serviceType, implementationType, name, policies);
        }
 /// <summary>
 /// Remove the currently tracked resolvers from the given policy list.
 /// </summary>
 /// <param name="policies">Policy list to remove the resolvers from.</param>
 public void RemoveResolvers(IPolicyList policies)
 {
     foreach(object key in keys)
     {
         policies.Clear<IDependencyResolverPolicy>(key);
     }
     keys.Clear();
 }
 public static TPolicyInterface GetPolicy <TPolicyInterface>(this IPolicyList list, INamedType buildKey, out IPolicyList containingPolicyList)
 {
     return((TPolicyInterface)(list.GetPolicyForKey(typeof(TPolicyInterface), buildKey, out containingPolicyList)
                               ?? (buildKey.Type.GetTypeInfo().IsGenericType
                                   ? list.Get(buildKey.Type.GetGenericTypeDefinition(), buildKey.Name, typeof(TPolicyInterface), out containingPolicyList) ??
                                   list.Get(null, null, typeof(TPolicyInterface), out containingPolicyList)
                                   : list.Get(null, null, typeof(TPolicyInterface), out containingPolicyList))));
 }
Example #34
0
        public static void Set <TPolicyInterface>(this IPolicyList policies, TPolicyInterface policy,
                                                  object buildKey)
            where TPolicyInterface : IBuilderPolicy
        {
            Guard.ArgumentNotNull(policies, "policies");

            policies.Set(typeof(TPolicyInterface), policy, buildKey);
        }
 /// <summary>
 /// Remove the resolvers for the given build key.
 /// </summary>
 /// <param name="policies">Policy list containing the build key.</param>
 /// <param name="buildKey">Build key.</param>
 public static void RemoveResolvers(IPolicyList policies, object buildKey)
 {
     IDependencyResolverTrackerPolicy tracker = policies.Get<IDependencyResolverTrackerPolicy>(buildKey);
     if (tracker != null)
     {
         tracker.RemoveResolvers(policies);
     }
 }
            public SelectedConstructor SelectConstructor(IBuilderContext context, IPolicyList resolverPoliciesDestination)
            {
                var selectedConstructor = new SelectedConstructor(typeof(T).GetConstructor(new[] { typeof(object) }));

                selectedConstructor.AddParameterResolver(this.parameterResolverPolicy);

                return(selectedConstructor);
            }
Example #37
0
        /// <summary>
        /// Add policies to the <paramref name="policies"/> to configure the
        /// container to call this constructor with the appropriate parameter values.
        /// </summary>
        /// <param name="serviceType">Type of interface registered, ignored in this implementation.</param>
        /// <param name="implementationType">Type to register.</param>
        /// <param name="name">Name used to resolve the type object.</param>
        /// <param name="policies">Policy list to add policies to.</param>
        public override void AddPolicies(Type serviceType, Type implementationType, string name, IPolicyList policies)
        {
            MethodInfo methodInfo = this.FindMethod(implementationType);
            this.ValidateMethodCanBeInjected(methodInfo, implementationType);

            SpecifiedMethodsSelectorPolicy selector =
                GetSelectorPolicy(policies, implementationType, name);
            selector.AddMethodAndParameters(methodInfo, this.methodParameters);
        }
Example #38
0
        /// <summary>
        /// Add policies to the <paramref name="policies"/> to configure the
        /// container to call this constructor with the appropriate parameter values.
        /// </summary>
        /// <param name="serviceType">Type of interface being registered. If no interface,
        /// this will be null. This parameter is ignored in this implementation.</param>
        /// <param name="implementationType">Type of concrete type being registered.</param>
        /// <param name="name">Name used to resolve the type object.</param>
        /// <param name="policies">Policy list to add policies to.</param>
        public override void AddPolicies(Type serviceType, Type implementationType, string name, IPolicyList policies)
        {
            Guard.ArgumentNotNull(implementationType, "implementationType");
            Guard.ArgumentNotNull(policies, "policies");

            var policy = new FactoryDelegateBuildPlanPolicy(this.factoryFunc);
            policies.Set<IBuildPlanPolicy>(policy,
                new NamedTypeBuildKey(implementationType, name));
        }
 private static IBuilderPolicy GetPolicyForType(this IPolicyList list, Type policyInterface, Type buildType, out IPolicyList containingPolicyList)
 {
     if (buildType != null)
     {
         return(list.Get(policyInterface, buildType, out containingPolicyList));
     }
     containingPolicyList = null;
     return(null);
 }
 private static IBuilderPolicy GetPolicyForOpenGenericType(this IPolicyList list, Type policyInterface, Type buildType, out IPolicyList containingPolicyList)
 {
     if (buildType != null && buildType.GetTypeInfo().IsGenericType)
     {
         return(list.Get(policyInterface, buildType.GetGenericTypeDefinition(), out containingPolicyList));
     }
     containingPolicyList = null;
     return(null);
 }
 private Type GetMappedType(IPolicyList policies)
 {
     var mappingPolicy = policies.Get<IBuildKeyMappingPolicy>(buildKey);
     if (mappingPolicy != null)
     {
         return mappingPolicy.Map(buildKey, null).Type;
     }
     return buildKey.Type;
 }
Example #42
0
 /// <summary>
 /// Create a new <see cref="BuilderContext"/> using the explicitly provided
 /// values.
 /// </summary>
 /// <param name="chain">The <see cref="IStrategyChain"/> to use for this context.</param>
 /// <param name="lifetime">The <see cref="ILifetimeContainer"/> to use for this context.</param>
 /// <param name="persistentPolicies">The set of persistent policies to use for this context.</param>
 /// <param name="transientPolicies">The set of transient policies to use for this context. It is
 /// the caller's responsibility to ensure that the transient and persistent policies are properly
 /// combined.</param>
 /// <param name="buildKey">Build key for this context.</param>
 /// <param name="existing">Existing object to build up.</param>
 public BuilderContext(IStrategyChain chain, ILifetimeContainer lifetime, IPolicyList persistentPolicies, IPolicyList transientPolicies, NamedTypeBuildKey buildKey, object existing)
 {
     this.chain = chain;
     this.lifetime = lifetime;
     this.persistentPolicies = persistentPolicies;
     this.policies = transientPolicies;
     this.originalBuildKey = buildKey;
     this.BuildKey = buildKey;
     this.Existing = existing;
 }
Example #43
0
 private static SpecifiedMethodsSelectorPolicy GetSelectorPolicy(IPolicyList policies, Type typeToCreate, string name)
 {
     var key = new NamedTypeBuildKey(typeToCreate, name);
     var selector = policies.GetNoDefault<IMethodSelectorPolicy>(key, false);
     if (selector == null || !(selector is SpecifiedMethodsSelectorPolicy))
     {
         selector = new SpecifiedMethodsSelectorPolicy();
         policies.Set<IMethodSelectorPolicy>(selector, key);
     }
     return (SpecifiedMethodsSelectorPolicy)selector;
 }
 public override void AddPolicies(Type serviceType, Type implementationType, string name, IPolicyList policies)
 {
     if (serviceType == null)
         throw new ArgumentNullException(nameof(serviceType), "The service type cannot be null");
     if (implementationType == null)
         throw new ArgumentNullException(nameof(implementationType), "The implementation type cannot be null");
     policies.Set(
         typeof(ILazyProxyPolicy),
         new LazyProxyPolicy(serviceType, implementationType),
         new NamedTypeBuildKey(serviceType, name));
 }
 /// <summary>
 /// Add policies to the <paramref name="policies"/> to configure the
 /// container to call this constructor with the appropriate parameter values.
 /// </summary>
 /// <param name="serviceType">Type of interface being registered. If no interface,
 /// this will be null.</param>
 /// <param name="implementationType">Type of concrete type being registered.</param>
 /// <param name="name">Name used to resolve the type object.</param>
 /// <param name="policies">Policy list to add policies to.</param>
 public override void AddPolicies(Type serviceType, Type implementationType, string name, IPolicyList policies)
 {
     if(IsInstanceInterceptor)
     {
         AddDefaultInstanceInterceptor(implementationType, policies);
     }
     else
     {
         AddDefaultTypeInterceptor(implementationType, policies);
     }
 }
Example #46
0
 /// <summary>
 /// Add policies to the <paramref name="policies"/> to configure the container to use the represented 
 /// <see cref="IInterceptionBehavior"/> for the supplied parameters.
 /// </summary>
 /// <param name="serviceType">Interface being registered.</param>
 /// <param name="implementationType">Type to register.</param>
 /// <param name="name">Name used to resolve the type object.</param>
 /// <param name="policies">Policy list to add policies to.</param>
 public override void AddPolicies(Type serviceType, Type implementationType, string name, IPolicyList policies)
 {
     if (this.explicitBehavior != null)
     {
         this.AddExplicitBehaviorPolicies(implementationType, name, policies);
     }
     else
     {
         this.AddKeyedPolicies(implementationType, name, policies);
     }
 }
 /// <summary>
 /// Add dependency resolvers to the policy set.
 /// </summary>
 /// <param name="policies">PolicyList to add the resolvers to.</param>
 /// <param name="parameterValues">Objects supplying the dependency resolvers.</param>
 /// <param name="result">Result object to store the keys in.</param>
 public static void AddParameterResolvers(IPolicyList policies, 
     IEnumerable<InjectionParameterValue> parameterValues, 
     SelectedMemberWithParameters result)
 {
     foreach(InjectionParameterValue parameterValue in parameterValues)
     {
         string key = Guid.NewGuid().ToString();
         policies.Set<IDependencyResolverPolicy>(parameterValue.GetResolverPolicy(), key);
         result.AddParameterKey(key);
     }
 }
 /// <summary>
 /// Get the list of behaviors for the current type so that it can be added to.
 /// </summary>
 /// <param name="policies">Policy list.</param>
 /// <param name="implementationType">Implementation type to set behaviors for.</param>
 /// <param name="name">Name type is registered under.</param>
 /// <returns>An instance of <see cref="InterceptionBehaviorsPolicy"/>.</returns>
 protected override InterceptionBehaviorsPolicy GetBehaviorsPolicy(IPolicyList policies, Type implementationType,
     string name)
 {
     var policy = policies.GetNoDefault<IInterceptionBehaviorsPolicy>(implementationType, false);
     if ((policy == null) || !(policy is InterceptionBehaviorsPolicy))
     {
         policy = new InterceptionBehaviorsPolicy();
         policies.Set(policy, implementationType);
     }
     return (InterceptionBehaviorsPolicy) policy;
 }
Example #49
0
 /// <summary>
 /// Create a new <see cref="BuilderContext"/> using the explicitly provided
 /// values.
 /// </summary>
 /// <param name="chain">The <see cref="IStrategyChain"/> to use for this context.</param>
 /// <param name="locator">The <see cref="IReadWriteLocator"/> to use for this context.</param>
 /// <param name="lifetime">The <see cref="ILifetimeContainer"/> to use for this context.</param>
 /// <param name="persistentPolicies">The set of persistent policies to use for this context.</param>
 /// <param name="transientPolicies">The set of transient policies to use for this context. It is
 /// the caller's responsibility to ensure that the transient and persistent policies are properly
 /// combined.</param>
 /// <param name="buildKey">Build key for this context.</param>
 /// <param name="existing">Existing object to build up.</param>
 public BuilderContext(IStrategyChain chain, IReadWriteLocator locator, ILifetimeContainer lifetime, IPolicyList persistentPolicies, IPolicyList transientPolicies, object buildKey, object existing)
 {
     this.chain = chain;
     this.lifetime = lifetime;
     this.locator = locator;
     this.persistentPolicies = persistentPolicies;
     this.policies = transientPolicies;
     this.originalBuildKey = buildKey;
     this.buildKey = buildKey;
     this.existing = existing;
 }
 // Helper methods for adding and removing the tracker policy.
 /// <summary>
 /// Get an instance that implements <see cref="IDependencyResolverTrackerPolicy"/>,
 /// either the current one in the policy set or creating a new one if it doesn't
 /// exist.
 /// </summary>
 /// <param name="policies">Policy list to look up from.</param>
 /// <param name="buildKey">Build key to track.</param>
 /// <returns>The resolver tracker.</returns>
 public static IDependencyResolverTrackerPolicy GetTracker(IPolicyList policies, object buildKey)
 {
     IDependencyResolverTrackerPolicy tracker =
         policies.Get<IDependencyResolverTrackerPolicy>(buildKey);
     if (tracker == null)
     {
         tracker = new DependencyResolverTrackerPolicy();
         policies.Set<IDependencyResolverTrackerPolicy>(tracker, buildKey);
     }
     return tracker;
 }
Example #51
0
 /// <summary>
 /// Create a new <see cref="BuilderContext"/> using the explicitly provided
 /// values.
 /// </summary>
 /// <param name="chain">The <see cref="IStrategyChain"/> to use for this context.</param>
 /// <param name="lifetime">The <see cref="ILifetimeContainer"/> to use for this context.</param>
 /// <param name="persistentPolicies">The set of persistent policies to use for this context.</param>
 /// <param name="transientPolicies">The set of transient policies to use for this context. It is
 /// the caller's responsibility to ensure that the transient and persistent policies are properly
 /// combined.</param>
 /// <param name="buildKey">Build key for this context.</param>
 /// <param name="existing">Existing object to build up.</param>
 public BuilderContext(IStrategyChain chain, ILifetimeContainer lifetime, IPolicyList persistentPolicies, IPolicyList transientPolicies, NamedTypeBuildKey buildKey, object existing)
 {
     this.chain = chain;
     this.lifetime = lifetime;
     this.persistentPolicies = persistentPolicies;
     this.policies = transientPolicies;
     this.originalBuildKey = buildKey;
     this.BuildKey = buildKey;
     this.Existing = existing;
     this.resolverOverrides = new CompositeResolverOverride();
     this.ownsOverrides = true;
 }
 public override void AddPolicies(Type serviceType, Type implementationType, string name, IPolicyList policies)
 {
     var key = new NamedTypeBuildKey(implementationType, name);
     var policy = policies.Get<InterceptorPolicy>(key);
     if (policy == null)
     {
         policy = new InterceptorPolicy();
         policies.Set(policy, key);
     }
     
     policy.AddInterceptor(this.interceptorContainer);
 }
        private void AddExplicitBehaviorPolicies(Type implementationType, string name, IPolicyList policies)
        {
            var lifetimeManager = new ContainerControlledLifetimeManager();
            lifetimeManager.SetValue(explicitBehavior);
            var behaviorName = Guid.NewGuid().ToString();
            var newBehaviorKey = new NamedTypeBuildKey(explicitBehavior.GetType(), behaviorName);

            policies.Set<ILifetimePolicy>(lifetimeManager, newBehaviorKey);

            InterceptionBehaviorsPolicy behaviorsPolicy = GetBehaviorsPolicy(policies, implementationType, name);
            behaviorsPolicy.AddBehaviorKey(newBehaviorKey);
        }
Example #54
0
 /// <summary>
 ///   Initialize a new instance of the <see cref = "BuilderContext" /> class with a <see cref = "IStrategyChain" />, 
 ///   <see cref = "ILifetimeContainer" />, <see cref = "IPolicyList" /> and the 
 ///   build key used to start this build operation.
 /// </summary>
 /// <param name = "chain">The <see cref = "IStrategyChain" /> to use for this context.</param>
 /// <param name = "lifetime">The <see cref = "ILifetimeContainer" /> to use for this context.</param>
 /// <param name = "policies">The <see cref = "IPolicyList" /> to use for this context.</param>
 /// <param name = "originalBuildKey">Build key to start building.</param>
 /// <param name = "existing">The existing object to build up.</param>
 public BuilderContext(IStrategyChain chain,
     ILifetimeContainer lifetime,
     IPolicyList policies,
     NamedTypeBuildKey originalBuildKey,
     object existing)
 {
     this.chain = chain;
     this.lifetime = lifetime;
     this.originalBuildKey = originalBuildKey;
     BuildKey = originalBuildKey;
     persistentPolicies = policies;
     this.policies = new PolicyList(persistentPolicies);
     Existing = existing;
 }
        public override void AddPolicies(Type typeToCreate, string name, IPolicyList policies)
        {
            Guard.ArgumentNotNull(typeToCreate, "typeToCreate");
             PropertyInfo propInfo = typeToCreate.GetProperty(propertyName);
             GuardPropertyExists(propInfo, typeToCreate, propertyName);
             GuardPropertyIsSettable(propInfo);
             GuardPropertyIsNotIndexer(propInfo);
             InitializeParameterValue(propInfo);
             GuardPropertyValueIsCompatible(propInfo, parameterValue);

             SpecifiedPropertiesSelectorPolicy selector =
             GetSelectorPolicy(policies, typeToCreate, name);

             selector.AddPropertyAndValue(propInfo, parameterValue);
        }
        /// <summary>
        /// Add dependency resolvers to the parameter set.
        /// </summary>
        /// <param name="typeToBuild">Type that's currently being built (used to resolve open generics).</param>
        /// <param name="policies">PolicyList to add the resolvers to.</param>
        /// <param name="parameterValues">Objects supplying the dependency resolvers.</param>
        /// <param name="result">Result object to store the keys in.</param>
        public static void AddParameterResolvers(Type typeToBuild,
            IPolicyList policies,
            IEnumerable<InjectionParameterValue> parameterValues,
            SelectedMemberWithParameters result)
        {
            Microsoft.Practices.Unity.Utility.Guard.ArgumentNotNull(policies, "policies");
            Microsoft.Practices.Unity.Utility.Guard.ArgumentNotNull(parameterValues, "parameterValues");
            Microsoft.Practices.Unity.Utility.Guard.ArgumentNotNull(result, "result");

            foreach (InjectionParameterValue parameterValue in parameterValues)
            {
                var resolver = parameterValue.GetResolverPolicy(typeToBuild);
                result.AddParameterResolver(resolver);
            }
        }
 internal static InterceptionBehaviorsPolicy GetOrCreate(
     IPolicyList policies,
     Type typeToCreate,
     string name)
 {
     NamedTypeBuildKey key = new NamedTypeBuildKey(typeToCreate, name);
     IInterceptionBehaviorsPolicy policy =
         policies.GetNoDefault<IInterceptionBehaviorsPolicy>(key, false);
     if ((policy == null) || !(policy is InterceptionBehaviorsPolicy))
     {
         policy = new InterceptionBehaviorsPolicy();
         policies.Set<IInterceptionBehaviorsPolicy>(policy, key);
     }
     return (InterceptionBehaviorsPolicy)policy;
 }
Example #58
0
        /// <summary>
        /// Add policies to the <paramref name="policies"/> to configure the
        /// container to call this constructor with the appropriate parameter values.
        /// </summary>
        /// <param name="typeToCreate">Type to register.</param>
        /// <param name="name">Name used to resolve the type object.</param>
        /// <param name="policies">Policy list to add policies to.</param>
        public override void AddPolicies(Type typeToCreate, string name, IPolicyList policies)
        {
            MethodInfo methodInfo = typeToCreate.GetMethod(methodName,
                Sequence.ToArray(
                    Sequence.Map<InjectionParameterValue, Type>(methodParameters,
                        delegate(InjectionParameterValue value)
                        {
                            return value.ParameterType;
                        })));
            ValidateMethodCanBeInjected(methodInfo, typeToCreate);

            SpecifiedMethodsSelectorPolicy selector =
                GetSelectorPolicy(policies, typeToCreate, name);
            selector.AddMethodAndParameters(methodInfo, methodParameters);
        }
 internal static AdditionalInterfacesPolicy GetOrCreate(
     IPolicyList policies,
     Type typeToCreate,
     string name)
 {
     NamedTypeBuildKey key = new NamedTypeBuildKey(typeToCreate, name);
     IAdditionalInterfacesPolicy policy =
         policies.GetNoDefault<IAdditionalInterfacesPolicy>(key, false);
     if ((policy == null) || !(policy is AdditionalInterfacesPolicy))
     {
         policy = new AdditionalInterfacesPolicy();
         policies.Set<IAdditionalInterfacesPolicy>(policy, key);
     }
     return (AdditionalInterfacesPolicy)policy;
 }
        /// <summary>
        /// Add policies to the <paramref name="policies"/> to configure the
        ///             container to call this constructor with the appropriate parameter values.
        /// </summary>
        /// <param name="serviceType">Type of interface being registered. If no interface,
        ///             this will be null.</param><param name="implementationType">Type of concrete type being registered.</param><param name="name">Name used to resolve the type object.</param><param name="policies">Policy list to add policies to.</param>
        public override void AddPolicies(Type serviceType, Type implementationType, string name, IPolicyList policies)
        {
            if (implementationType == null) throw new ArgumentNullException("implementationType");

            if(!implementationType.IsGenericType ||
                implementationType.GetGenericTypeDefinition() != typeof(Validator<>))
            {
                throw new InvalidOperationException(Resources.IllegalUseOfInjectionValidationSource);
            }

            var key = new NamedTypeBuildKey(implementationType, name);
            var policy = new ValidationSpecificationSourcePolicy(Source);

            policies.Set<ValidationSpecificationSourcePolicy>(policy, key);
        }