コード例 #1
0
			private static SelectedConstructor FindNewConstructor(SelectedConstructor originalConstructor, Type interceptingType)
			{
				var originalParams = originalConstructor.Constructor.GetParameters();

				var newConstructorInfo = interceptingType.GetConstructor(originalParams.Select(pi => pi.ParameterType).ToArray());

				var newConstructor = new SelectedConstructor(newConstructorInfo);

				foreach (var key in originalConstructor.GetParameterKeys())
				{
					newConstructor.AddParameterKey(key);
				}

				return newConstructor;
			}
コード例 #2
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)
        {
            SelectedConstructor result;
            Type typeToBuild = context.BuildKey.Type;

            ReflectionHelper typeReflector = new ReflectionHelper(ctor.DeclaringType);
            if (!ctorReflector.MethodHasOpenGenericParameters && !typeReflector.IsOpenGeneric)
            {
                result = new SelectedConstructor(ctor);
            }
            else
            {
                Type[] closedCtorParameterTypes =
                    ctorReflector.GetClosedParameterTypes(typeToBuild.GetGenericArguments());
                result = new SelectedConstructor(typeToBuild.GetConstructor(closedCtorParameterTypes));
            }

            SpecifiedMemberSelectorHelper.AddParameterResolvers(typeToBuild, resolverPolicyDestination, parameterValues, result);
            return result;
        }
コード例 #3
0
 private static void ResolveConstructorParameters(SelectedConstructor constructor, Dictionary<string, StepScopeDependency> constructorParameters)
 {
     var parameterResolvers = constructor.GetParameterResolvers();
     for (var i = 0; i < parameterResolvers.Length; i++)
     {
         var namedTypeResolver = parameterResolvers[i] as NamedTypeDependencyResolverPolicy;
         if (namedTypeResolver != null)
         {
             var type = namedTypeResolver.Type;
             var name = namedTypeResolver.Name;
             if (StepScopeSynchronization.IsStepScope(type, name))
             {
                 var parameter = constructor.Constructor.GetParameters()[i];
                 constructorParameters[parameter.Name] = new StepScopeDependency(type, name);
             }
         }
     }
 }
コード例 #4
0
        private IEnumerable<Expression> CreateNewBuildupSequence(DynamicBuildPlanGenerationContext buildContext, SelectedConstructor selectedConstructor, string signature)
        {
            var parameterExpressions = BuildConstructionParameterExpressions(buildContext, selectedConstructor, signature);
            var newItemExpression = Expression.Variable(selectedConstructor.Constructor.DeclaringType, "newItem");

            yield return Expression.Call(null,
                                        setCurrentOperationToInvokingConstructor,
                                        Expression.Constant(signature),
                                        buildContext.ContextParameter
                                        );

            yield return Expression.Assign(
                            buildContext.GetExistingObjectExpression(),
                            Expression.Convert(
                                Expression.New(selectedConstructor.Constructor, parameterExpressions),
                                typeof(object)));

            yield return buildContext.GetClearCurrentOperationExpression();
        }
コード例 #5
0
        private IEnumerable<Expression> BuildConstructionParameterExpressions(DynamicBuildPlanGenerationContext buildContext, SelectedConstructor selectedConstructor, string constructorSignature)
        {
            int i = 0;
            var constructionParameters = selectedConstructor.Constructor.GetParameters();

            foreach (string parameterKey in selectedConstructor.GetParameterKeys())
            {
                yield return buildContext.CreateParameterExpression(
                                parameterKey,
                                constructionParameters[i].ParameterType,
                                Expression.Call(null,
                                                setCurrentOperationToResolvingParameter,
                                                Expression.Constant(constructionParameters[i].Name, typeof(string)),
                                                Expression.Constant(constructorSignature),
                                                buildContext.ContextParameter
                                                )
                                );
                i++;
            }
        }
コード例 #6
0
 private static bool IsInvalidConstructor(SelectedConstructor selectedConstructor)
 {
     return selectedConstructor.Constructor.GetParameters().Any(pi => pi.ParameterType.IsByRef);
 }
コード例 #7
0
 // Verify the type we're trying to build is actually constructable -
 // CLR primitive types like string and int aren't.
 private static void GuardTypeIsNonPrimitive(IBuilderContext context, SelectedConstructor selectedConstructor)
 {
     var typeToBuild = context.BuildKey.Type;
     if (!typeToBuild.GetTypeInfo().IsInterface)
     {
         if (typeToBuild == typeof(string))
         {
             throw new InvalidOperationException(
                 string.Format(
                     CultureInfo.CurrentCulture,
                     Resources.TypeIsNotConstructable,
                     typeToBuild.GetTypeInfo().Name));
         }
     }
 }
コード例 #8
0
        internal Expression CreateInstanceBuildupExpression(DynamicBuildPlanGenerationContext buildContext, SelectedConstructor selectedConstructor)
        {
            IEnumerable<Expression> buildupSequence;

            string signature = CreateSignatureString(selectedConstructor.Constructor);

            buildupSequence = IsInvalidConstructor(selectedConstructor)?
                                CreateThrowForNullExistingObjectWithInvalidConstructorSequence(buildContext, signature) :
                                CreateNewBuildupSequence(buildContext, selectedConstructor, signature);

            // psuedo-code:
            // throw if attempting interface
            // if (context.Existing == null) {
            //   collect parameters
            //   set operation to invoking constructor
            //   context.Existing = new {objectType}({constructorparameter}...)
            //   clear current operation
            // }
            return
                Expression.Block(
                   Expression.Call(null, throwForAttemptingToConstructInterface, buildContext.ContextParameter),
                   Expression.Block(buildupSequence));
        }
コード例 #9
0
            public SelectedConstructor SelectConstructor(IBuilderContext context, IPolicyList resolverPoliciesDestination)
            {
                var ctr = typeof(InjectedObject).GetMatchingConstructor(new[] { typeof(object) });
                var selectedConstructor = new SelectedConstructor(ctr);
                selectedConstructor.AddParameterResolver(this.resolverPolicy);

                return selectedConstructor;
            }
 /// <summary>
 /// Create a new <see cref="ConstructorWithResolverKeysSelectorPolicy"/> instance.
 /// </summary>
 /// <param name="selectedConstructor">Information about which constructor to select.</param>
 public ConstructorWithResolverKeysSelectorPolicy(SelectedConstructor selectedConstructor)
 {
     this.selectedConstructor = selectedConstructor;
 }
        //Boolean IsRegistered( IBuilderContext context, Type key )
        //{
        //	var policy = context.PersistentPolicies.Get<IBuildKeyMappingPolicy>( key );

        //	return policy != null;
        //}

        public SelectedConstructor SelectConstructor(IBuilderContext context, IPolicyList resolverPolicyDestination)
        {
            var ctor = this.implementationType.GetConstructors()
                       .FirstOrDefault(x =>
            {
                return(!x.IsStatic && x.GetParameters()
                       .All(y =>
                {
                    var pti = y.ParameterType;

                    //if ( entry.Parameters.ContainsKey( y.Name ) && pti.IsAssignableFrom( entry.Parameters[ y.Name ].GetType() ) )
                    //{
                    //	return true;
                    //}


                    //if ( this.IsRegistered( context, pti ) )
                    //{
                    //	return true;
                    //}
                    if (this.container.IsRegistered(pti))
                    {
                        return true;
                    }

                    if (pti.IsArray && pti.HasElementType)
                    {
                        var eti = pti.GetElementType();

                        return this.container.IsRegistered(eti);

                        //return this.IsRegistered( context, eti );
                    }

                    if (pti.IsGenericType)
                    {
                        //is "IEnumerable"
                    }

                    return false;
                }));
            });

            Ensure.That(ctor)
            .Named("ctor")
            .WithMessage("Cannot find any valid constructor fot type {0}.", implementationType.FullName)
            .IsNotNull();

            //var parameterValues = new List<Object>();

            var values = ctor.GetParameters()
                         .Aggregate(new List <Object>(), (objs, p) =>
            {
                objs.Add(p.ParameterType);
                return(objs);
            })
                         .Select(o => InjectionParameterValue.ToParameter(o))
                         .ToArray();

            //.ForEach( p =>
            //{
            //	parameterValues.Add( p.ParameterType );
            //} );

            //var values = InjectionParameterValue.ToParameters( parameterValues.ToArray() );

            var selectedCtor = new SelectedConstructor(ctor);

            SpecifiedMemberSelectorHelper.AddParameterResolvers(this.implementationType, resolverPolicyDestination, values, selectedCtor);

            return(selectedCtor);
        }
コード例 #12
0
 /// <summary>
 /// Create a new <see cref="ConstructorWithResolverKeysSelectorPolicy"/> instance.
 /// </summary>
 /// <param name="selectedConstructor">Information about which constructor to select.</param>
 public ConstructorWithResolverKeysSelectorPolicy(SelectedConstructor selectedConstructor)
 {
     this.selectedConstructor = selectedConstructor;
 }
コード例 #13
0
        private IEnumerable <Expression> BuildConstructionParameterExpressions(DynamicBuildPlanGenerationContext buildContext, SelectedConstructor selectedConstructor, string constructorSignature)
        {
            int i = 0;
            var constructionParameters = selectedConstructor.Constructor.GetParameters();

            foreach (IResolverPolicy parameterResolver in selectedConstructor.GetParameterResolvers())
            {
                yield return(buildContext.CreateParameterExpression(
                                 parameterResolver,
                                 constructionParameters[i].ParameterType,
                                 Expression.Call(null,
                                                 SetCurrentOperationToResolvingParameterMethod,
                                                 Expression.Constant(constructionParameters[i].Name, typeof(string)),
                                                 Expression.Constant(constructorSignature),
                                                 buildContext.ContextParameter)));

                i++;
            }
        }
コード例 #14
0
        private IEnumerable <Expression> CreateNewBuildupSequence(DynamicBuildPlanGenerationContext buildContext, SelectedConstructor selectedConstructor, string signature)
        {
            var parameterExpressions = BuildConstructionParameterExpressions(buildContext, selectedConstructor, signature);
            var newItemExpression    = Expression.Variable(selectedConstructor.Constructor.DeclaringType, "newItem");

            yield return(Expression.Call(null,
                                         SetCurrentOperationToInvokingConstructorMethod,
                                         Expression.Constant(signature),
                                         buildContext.ContextParameter));

            yield return(Expression.Assign(
                             buildContext.GetExistingObjectExpression(),
                             Expression.Convert(
                                 Expression.New(selectedConstructor.Constructor, parameterExpressions),
                                 typeof(object))));

            yield return(buildContext.GetClearCurrentOperationExpression());
        }
コード例 #15
0
        private static bool IsInvalidConstructor(TypeInfo target, IBuilderContext context, SelectedConstructor selectedConstructor)
        {
            if (selectedConstructor.Constructor.GetParameters().Any(p => p.ParameterType.GetTypeInfo() == target))
            {
                var policy = (ILifetimePolicy)context.Policies.Get(context.BuildKey.Type,
                                                                   context.BuildKey.Name,
                                                                   typeof(ILifetimePolicy), out var _);
                if (null == policy?.GetValue())
                {
                    return(true);
                }
            }

            return(false);
        }
コード例 #16
0
 /// <summary>
 /// Choose the constructor to call for the given type.
 /// </summary>
 /// <param name="context">Current build context</param>
 /// <returns>The chosen constructor.</returns>
 public SelectedConstructor SelectConstructor(IBuilderContext context)
 {
     SelectedConstructor result = new SelectedConstructor(ctor);
     SpecifiedMemberSelectorHelper.AddParameterResolvers(context.PersistentPolicies, parameterValues, result);
     return result;
 }
コード例 #17
0
            public SelectedConstructor SelectConstructor(IBuilderContext context, IPolicyList resolverPoliciesDestination)
            {
                SelectedConstructor selectedConstructor
                    = new SelectedConstructor(typeof(InjectedObject).GetMatchingConstructor(new Type[] { typeof(object) }));
                selectedConstructor.AddParameterKey("InjectedObject_injectedValue");
                resolverPoliciesDestination.Set<IDependencyResolverPolicy>(this.resolverPolicy, "InjectedObject_injectedValue");

                return selectedConstructor;
            }
		//Boolean IsRegistered( IBuilderContext context, Type key ) 
		//{
		//	var policy = context.PersistentPolicies.Get<IBuildKeyMappingPolicy>( key );

		//	return policy != null;
		//}

		public SelectedConstructor SelectConstructor( IBuilderContext context, IPolicyList resolverPolicyDestination )
		{
			var ctor = this.implementationType.GetConstructors()
				.FirstOrDefault( x =>
				{
					return !x.IsStatic && x.GetParameters()
						.All( y =>
						{
							var pti = y.ParameterType;

							//if ( entry.Parameters.ContainsKey( y.Name ) && pti.IsAssignableFrom( entry.Parameters[ y.Name ].GetType() ) )
							//{
							//	return true;
							//}


							//if ( this.IsRegistered( context, pti ) )
							//{
							//	return true;
							//}
							if ( this.container.IsRegistered( pti ) )
							{
								return true;
							}

							if ( pti.IsArray && pti.HasElementType )
							{
								var eti = pti.GetElementType();

								return this.container.IsRegistered( eti );

								//return this.IsRegistered( context, eti );
							}

							if ( pti.IsGenericType )
							{
								//is "IEnumerable"
							}

							return false;
						} );
				} );

			Ensure.That( ctor )
					.Named( "ctor" )
					.WithMessage( "Cannot find any valid constructor fot type {0}.", implementationType.FullName )
					.IsNotNull();

			//var parameterValues = new List<Object>();
			
			var values = ctor.GetParameters()
				.Aggregate( new List<Object>(), ( objs, p ) =>
				{
					objs.Add( p.ParameterType );
					return objs;
				} )
				.Select( o => InjectionParameterValue.ToParameter( o ) )
				.ToArray();

			//.ForEach( p =>
			//{
			//	parameterValues.Add( p.ParameterType );
			//} );

			//var values = InjectionParameterValue.ToParameters( parameterValues.ToArray() );

			var selectedCtor = new SelectedConstructor( ctor );
			SpecifiedMemberSelectorHelper.AddParameterResolvers( this.implementationType, resolverPolicyDestination, values, selectedCtor );

			return selectedCtor;
		}