コード例 #1
0
ファイル: Context.cs プロジェクト: Temka193/behaviour_inject
        private ConstructorInfo FindAppropriateConstructor(Type resolvingType)
        {
            ConstructorInfo[] constructors = resolvingType.GetConstructors();

            ConstructorInfo constructorWithLeastArguments = null;
            int             leastParameters = Int32.MaxValue;

            for (int i = 0; i < constructors.Length; i++)
            {
                ConstructorInfo constructor = constructors[i];

                if (AttributeUtils.IsMarked <InjectAttribute>(constructor))
                {
                    return(constructor);
                }

                int parametersLength = constructor.GetParameters().Length;
                if (parametersLength < leastParameters)
                {
                    constructorWithLeastArguments = constructor;
                    leastParameters = parametersLength;
                }
            }

            if (constructorWithLeastArguments == null)
            {
                throw new BehaviourInjectException("Can not find constructor for type " + resolvingType.FullName);
            }

            return(constructorWithLeastArguments);
        }
コード例 #2
0
        public object AutocomposeDependency(Type resolvingType)
        {
            CheckAgainstCompositionStack(resolvingType);
            _compositionStack.Push(resolvingType);

            ConstructorInfo constructor = FindAppropriateConstructor(resolvingType);

            ParameterInfo[] parameters = constructor.GetParameters();
            object[]        arguments  = new object[parameters.Length];

            for (int i = 0; i < parameters.Length; i++)
            {
                ParameterInfo parameter    = parameters[i];
                Type          argumentType = parameter.ParameterType;

                object dependency;
                if (AttributeUtils.IsMarked <CreateAttribute>(parameter))
                {
                    dependency = AutocomposeDependency(argumentType);
                }
                else
                {
                    if (!TryResolve(argumentType, out dependency))
                    {
                        throw new BehaviourInjectException(String.Format(
                                                               "Could not resolve {0} for {2} in context {1}. Probably it's not registered",
                                                               argumentType.FullName, _name, resolvingType.FullName));
                    }
                }

                arguments[i] = dependency;
            }

            object result = constructor.Invoke(arguments);

            IMemberInjection[] injections = ReflectionCache.GetInjections(resolvingType);
            for (int i = 0; i < injections.Length; i++)
            {
                injections[i].Inject(result, this);
            }

            _compositionStack.Pop();

            return(result);
        }