public void SetUp()
        {
            _finder = new ConstructorFinder();

            _requestedType = typeof(RequestedType);
            _assembledType = typeof(AssembledType);
        }
        static ObjectFactory()
        {
            //var assembler = SafeServiceLocator.Current.GetInstance<IAssembler>();
            var declarationProvider = SafeServiceLocator.Current.GetInstance <IDeclarationProvider>();
            var adviceComposer      = new AdviceComposer(new PointcutEvaluator());
            var adviceWeaver        = SafeServiceLocator.Current.GetInstance <IAdviceWeaver>();
            var intertypeWeaver     = SafeServiceLocator.Current.GetInstance <IIntertypeWeaver>();
            var eventMethodPreparer = SafeServiceLocator.Current.GetInstance <IEventMethodPreparer>();
            var assembler           = new Participant(declarationProvider, adviceComposer, adviceWeaver, intertypeWeaver, eventMethodPreparer);


            var typeModifier      = SafeServiceLocator.Current.GetInstance <ITypeModifier>();
            var typeAssembler     = new TypeAssembler(new[] { assembler }, typeModifier);
            var constructorFinder = new ConstructorFinder();
            var delegateFactory   = new DelegateFactory();
            var typeCache         = new TypeCache(typeAssembler, constructorFinder, delegateFactory);

            s_objectFactory = new Remotion.TypePipe.ObjectFactory(typeCache);
        }
Esempio n. 3
0
        /// <summary>
        /// Activate an instance in the provided context.
        /// </summary>
        /// <param name="context">Context in which to activate instances.</param>
        /// <param name="parameters">Parameters to the instance.</param>
        /// <returns>The activated instance.</returns>
        /// <remarks>
        /// The context parameter here should probably be ILifetimeScope in order to reveal Disposer,
        /// but will wait until implementing a concrete use case to make the decision.
        /// </remarks>
        public object ActivateInstance(IComponentContext context, IEnumerable <Parameter> parameters)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            CheckNotDisposed();

            // Lazy instantiate available constructor list so the constructor
            // finder can be changed during AsSelf() registration. AsSelf() creates
            // a temporary activator just long enough to get the LimitType.
            if (_availableConstructors == null)
            {
                lock (_availableConstructorsLock)
                {
                    if (_availableConstructors == null)
                    {
                        _availableConstructors = ConstructorFinder.FindConstructors(_implementationType);
                    }
                }
            }

            if (_availableConstructors.Length == 0)
            {
                throw new DependencyResolutionException(string.Format(CultureInfo.CurrentCulture, ReflectionActivatorResources.NoConstructorsAvailable, _implementationType, ConstructorFinder));
            }

            var validBindings = GetValidConstructorBindings(_availableConstructors, context, parameters);

            var selectedBinding = ConstructorSelector.SelectConstructorBinding(validBindings, parameters);

            var instance = selectedBinding.Instantiate();

            InjectProperties(instance, context);

            return(instance);
        }
Esempio n. 4
0
        /// <summary>
        /// Activate an instance in the provided context.
        /// </summary>
        /// <param name="context">Context in which to activate instances.</param>
        /// <param name="parameters">Parameters to the instance.</param>
        /// <returns>The activated instance.</returns>
        /// <remarks>
        /// The context parameter here should probably be ILifetimeScope in order to reveal Disposer,
        /// but will wait until implementing a concrete use case to make the decision
        /// </remarks>
        public object ActivateInstance(IComponentContext context, IEnumerable <Parameter> parameters)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            var availableConstructors = ConstructorFinder.FindConstructors(_implementationType);

            if (availableConstructors.Length == 0)
            {
                throw new DependencyResolutionException(string.Format(
                                                            CultureInfo.CurrentCulture, ReflectionActivatorResources.NoConstructorsAvailable, _implementationType, ConstructorFinder));
            }

            var constructorBindings = GetConstructorBindings(
                context,
                parameters,
                availableConstructors);

            var validBindings = constructorBindings
                                .Where(cb => cb.CanInstantiate)
                                .ToArray();

            if (validBindings.Length == 0)
            {
                throw new DependencyResolutionException(GetBindingFailureMessage(constructorBindings));
            }

            var selectedBinding = ConstructorSelector.SelectConstructorBinding(validBindings);

            var instance = selectedBinding.Instantiate();

            InjectProperties(instance, context);

            return(instance);
        }
Esempio n. 5
0
        ConstructorInfo exec <T>(params object[] instances)
        {
            ConstructorParameters parameters = new ConstructorParameters();

            foreach (object instance in instances)
            {
                parameters.Add(new ConstructorParameter()
                {
                    Type  = instance.GetType(),
                    Value = instance
                });
            }

            ConstructorFinder finder = new ConstructorFinder();

            ConstructorInfo[]          allCtors  = typeof(T).GetConstructors();
            ConstructorListGenerator   generator = new ConstructorListGenerator(new ConstructorGenerator(new ParametersGenerator(new ParameterGenerator())));
            IEnumerable <IConstructor> ctors     = generator.GenerateList(allCtors);
            IConstructor ctor = finder.FindBy(ctors, parameters);

            return(ctor.Instance);
        }
Esempio n. 6
0
        /// <inheritdoc/>
        public void ConfigurePipeline(IComponentRegistryServices componentRegistryServices, IResolvePipelineBuilder pipelineBuilder)
        {
            if (componentRegistryServices is null)
            {
                throw new ArgumentNullException(nameof(componentRegistryServices));
            }

            if (pipelineBuilder is null)
            {
                throw new ArgumentNullException(nameof(pipelineBuilder));
            }

            // Locate the possible constructors at container build time.
            var availableConstructors = ConstructorFinder.FindConstructors(_implementationType);

            if (availableConstructors.Length == 0)
            {
                throw new NoConstructorsFoundException(_implementationType, string.Format(CultureInfo.CurrentCulture, ReflectionActivatorResources.NoConstructorsAvailable, _implementationType, ConstructorFinder));
            }

            var binders = new ConstructorBinder[availableConstructors.Length];

            for (var idx = 0; idx < availableConstructors.Length; idx++)
            {
                binders[idx] = new ConstructorBinder(availableConstructors[idx]);
            }

            _constructorBinders = binders;

            pipelineBuilder.Use(ToString(), PipelinePhase.Activation, MiddlewareInsertionMode.EndOfPhase, (ctxt, next) =>
            {
                ctxt.Instance = ActivateInstance(ctxt, ctxt.Parameters);

                next(ctxt);
            });
        }
Esempio n. 7
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private Object invokeInternal() throws Exception
        private Object InvokeInternal()
        {
            Object target     = Target;
            String methodName = MethodName;

            if (target == null || methodName == null)
            {
                throw new NullPointerException((target == null ? "target" : "methodName") + " should not be null");
            }

            Object[] arguments = Arguments;
            if (arguments == null)
            {
                arguments = EmptyArray;
            }
            // Class.forName() won't load classes outside
            // of core from a class inside core. Special
            // case this method.
            if (target == typeof(Class) && methodName.Equals("forName"))
            {
                return(ClassFinder.resolveClass((String)arguments[0], this.Loader));
            }
            Class[] argClasses = new Class[arguments.Length];
            for (int i = 0; i < arguments.Length; i++)
            {
                argClasses[i] = (arguments[i] == null) ? null : arguments[i].GetType();
            }

            AccessibleObject m = null;

            if (target is Class)
            {
                /*
                 * For class methods, simluate the effect of a meta class
                 * by taking the union of the static methods of the
                 * actual class, with the instance methods of "Class.class"
                 * and the overloaded "newInstance" methods defined by the
                 * constructors.
                 * This way "System.class", for example, will perform both
                 * the static method getProperties() and the instance method
                 * getSuperclass() defined in "Class.class".
                 */
                if (methodName.Equals("new"))
                {
                    methodName = "newInstance";
                }
                // Provide a short form for array instantiation by faking an nary-constructor.
                if (methodName.Equals("newInstance") && ((Class)target).Array)
                {
                    Object result = Array.newInstance(((Class)target).ComponentType, arguments.Length);
                    for (int i = 0; i < arguments.Length; i++)
                    {
                        Array.set(result, i, arguments[i]);
                    }
                    return(result);
                }
                if (methodName.Equals("newInstance") && arguments.Length != 0)
                {
                    // The Character class, as of 1.4, does not have a constructor
                    // which takes a String. All of the other "wrapper" classes
                    // for Java's primitive types have a String constructor so we
                    // fake such a constructor here so that this special case can be
                    // ignored elsewhere.
                    if (target == typeof(Character) && arguments.Length == 1 && argClasses[0] == typeof(String))
                    {
                        return(new Character(((String)arguments[0]).CharAt(0)));
                    }
                    try
                    {
                        m = ConstructorFinder.findConstructor((Class)target, argClasses);
                    }
                    catch (NoSuchMethodException)
                    {
                        m = null;
                    }
                }
                if (m == null && target != typeof(Class))
                {
                    m = GetMethod((Class)target, methodName, argClasses);
                }
                if (m == null)
                {
                    m = GetMethod(typeof(Class), methodName, argClasses);
                }
            }
            else
            {
                /*
                 * This special casing of arrays is not necessary, but makes files
                 * involving arrays much shorter and simplifies the archiving infrastrcure.
                 * The Array.set() method introduces an unusual idea - that of a static method
                 * changing the state of an instance. Normally statements with side
                 * effects on objects are instance methods of the objects themselves
                 * and we reinstate this rule (perhaps temporarily) by special-casing arrays.
                 */
                if (target.GetType().IsArray&& (methodName.Equals("set") || methodName.Equals("get")))
                {
                    int index = ((Integer)arguments[0]).IntValue();
                    if (methodName.Equals("get"))
                    {
                        return(Array.get(target, index));
                    }
                    else
                    {
                        Array.set(target, index, arguments[1]);
                        return(null);
                    }
                }
                m = GetMethod(target.GetType(), methodName, argClasses);
            }
            if (m != null)
            {
                try
                {
                    if (m is Method)
                    {
                        return(MethodUtil.invoke((Method)m, target, arguments));
                    }
                    else
                    {
                        return(((Constructor)m).newInstance(arguments));
                    }
                }
                catch (IllegalAccessException iae)
                {
                    throw new Exception("Statement cannot invoke: " + methodName + " on " + target.GetType(), iae);
                }
                catch (InvocationTargetException ite)
                {
                    Throwable te = ite.TargetException;
                    if (te is Exception)
                    {
                        throw (Exception)te;
                    }
                    else
                    {
                        throw ite;
                    }
                }
            }
            throw new NoSuchMethodException(ToString());
        }