/// <summary>
        /// The create instance.
        /// </summary>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <param name="type">
        /// The type.
        /// </param>
        /// <param name="nonPublic">
        /// The non public.
        /// </param>
        /// <returns>
        /// The create instance.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// </exception>
        public static object CreateInstance(this IComponentContext context, Type type, bool nonPublic)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            object res;

            if (context.TryResolve(type, out res))
            {
                return(res);
            }

            var a = new ReflectionActivator(
                type,
                new BindingFlagsConstructorFinder(nonPublic ? BindingFlags.NonPublic : BindingFlags.Public),
                new MostParametersConstructorSelector(),
                new Parameter[] { },
                new Parameter[] { });

            return(a.ActivateInstance(context, new Parameter[] { }));
        }
 /// <summary>
 /// Registers individual configured modules into a container builder.
 /// </summary>
 /// <param name="builder">
 /// The <see cref="Autofac.ContainerBuilder"/> that should receive the configured registrations.
 /// </param>
 /// <param name="configurationSection">
 /// The <see cref="Autofac.Configuration.SectionHandler"/> containing the configured registrations.
 /// </param>
 /// <exception cref="System.ArgumentNullException">
 /// Thrown if <paramref name="builder"/> or <paramref name="configurationSection"/> is <see langword="null"/>.
 /// </exception>
 /// <exception cref="System.Configuration.ConfigurationErrorsException">
 /// Thrown if there is any issue in parsing the module configuration into registrations.
 /// </exception>
 /// <remarks>
 /// <para>
 /// This is where the individually configured component registrations get added to the <paramref name="builder" />.
 /// The <see cref="Autofac.Configuration.SectionHandler.Modules"/> collection from the <paramref name="configurationSection" />
 /// get processed into individual modules which are instantiated and activated inside the <paramref name="builder" />.
 /// </para>
 /// </remarks>
 protected virtual void RegisterConfiguredModules(ContainerBuilder builder, SectionHandler configurationSection)
 {
     if (builder == null)
     {
         throw new ArgumentNullException("builder");
     }
     if (configurationSection == null)
     {
         throw new ArgumentNullException("configurationSection");
     }
     foreach (ModuleElement moduleElement in configurationSection.Modules)
     {
         var     moduleType = this.LoadType(moduleElement.Type, configurationSection.DefaultAssembly);
         IModule module     = null;
         using (var moduleActivator = new ReflectionActivator(
                    moduleType,
                    new DefaultConstructorFinder(),
                    new MostParametersConstructorSelector(),
                    moduleElement.Parameters.ToParameters(),
                    moduleElement.Properties.ToParameters()))
         {
             module = (IModule)moduleActivator.ActivateInstance(new ContainerBuilder().Build(), Enumerable.Empty <Parameter>());
         }
         builder.RegisterModule(module);
     }
 }
Exemple #3
0
    public virtual void RegisterConfiguredModules(ContainerBuilder builder, IConfiguration configuration)
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }
        if (configuration == null)
        {
            throw new ArgumentNullException(nameof(configuration));
        }
        var defaultAssembly = configuration.DefaultAssembly();

        foreach (var moduleElement in configuration.GetSection("modules").GetChildren())
        {
            var moduleTypeName = moduleElement["type"];
            var moduleType     = GetType(moduleTypeName, defaultAssembly);
            if (moduleType == null)
            {
                // Log moduleTypeName
                Console.WriteLine($"{moduleTypeName} module not found");
                continue;
            }
            var module = (IModule)null;
            using (var moduleActivator = new ReflectionActivator(
                       moduleType,
                       new DefaultConstructorFinder(),
                       new MostParametersConstructorSelector(),
                       moduleElement.GetParameters("parameters"),
                       moduleElement.GetProperties("properties")))
            {
                module = (IModule)moduleActivator.ActivateInstance(new ContainerBuilder().Build(), Enumerable.Empty <Parameter>());
            }
            builder.RegisterModule(module);
        }
    }
Exemple #4
0
        protected static void CreateClassProxy(IInterceptor[] interceptors, ActivatingEventArgs <object> e, Type type, object instance,
                                               Type[] proxiedInterfaces)
        {
            // Ensure we don't try to proxy anything that can't be proxied
            if (type.IsSealed)
            {
                return;
            }

            var targetType = type;

            // Special handling for nested proxies...
            if (ProxyUtil.IsProxy(instance))
            {
                OverrideProxyInterceptors(interceptors, instance);
            }
            else
            {
                var proxyType = ProxyGenerator.ProxyBuilder.CreateClassProxyType(targetType, proxiedInterfaces,
                                                                                 ProxyGenerationOptions.Default);

                var activator = new ReflectionActivator(proxyType,
                                                        new DefaultConstructorFinder(),
                                                        new MostParametersConstructorSelector(),
                                                        GetConfiguredParams(ProxyGenerationOptions.Default, interceptors),
                                                        Enumerable.Empty <Parameter>());

                e.ReplaceInstance(activator.ActivateInstance(e.Context, e.Parameters));

                // Dispose of the old instance, if necessary
                var oldInstance = instance as IDisposable;
                oldInstance?.Dispose();
            }
        }
        /// <summary>
        /// Registers individual configured modules into a container builder.
        /// </summary>
        /// <param name="builder">
        /// The <see cref="Autofac.ContainerBuilder"/> that should receive the configured registrations.
        /// </param>
        /// <param name="configuration">
        /// The <see cref="IConfiguration"/> containing the configured registrations.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown if <paramref name="builder"/> or <paramref name="configuration"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="System.InvalidOperationException">
        /// Thrown if there is any issue in parsing the module configuration into registrations.
        /// </exception>
        /// <remarks>
        /// <para>
        /// This is where the individually configured component registrations get added to the <paramref name="builder"/>.
        /// The <c>modules</c> collection from the <paramref name="configuration"/>
        /// get processed into individual modules which are instantiated and activated inside the <paramref name="builder"/>.
        /// </para>
        /// </remarks>
        public virtual void RegisterConfiguredModules(ContainerBuilder builder, IConfiguration configuration)
        {
            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            var defaultAssembly = configuration.DefaultAssembly();

            foreach (var moduleElement in configuration.GetConfigurationSection("modules").GetConfigurationSections().Select(kvp => kvp.Value))
            {
                var moduleType = moduleElement.GetType("type", defaultAssembly);
                var module     = (IModule)null;
                using (var moduleActivator = new ReflectionActivator(
                           moduleType,
                           new DefaultConstructorFinder(),
                           new MostParametersConstructorSelector(),
                           moduleElement.GetParameters("parameters"),
                           moduleElement.GetProperties("properties")))
                {
                    module = (IModule)moduleActivator.ActivateInstance(new ContainerBuilder().Build(), Enumerable.Empty <Parameter>());
                }
                builder.RegisterModule(module);
            }
        }
 private void RegisterConfiguredModule(ContainerBuilder builder, SectionHandler configurationSection, ModuleElement moduleElement)
 {
     try
     {
         var     moduleType = this.LoadType(moduleElement.Type, configurationSection.DefaultAssembly);
         IModule module     = null;
         IEnumerable <Parameter> parameters = moduleElement.Parameters.ToParameters().Select(p => new LazyParameter(p));
         IEnumerable <Parameter> properties = moduleElement.Properties.ToParameters().Select(p => new LazyParameter(p));
         using (var moduleActivator = new ReflectionActivator(
                    moduleType,
                    new DefaultConstructorFinder(),
                    new MostParametersConstructorSelector(),
                    parameters,
                    properties))
         {
             module = (IModule)moduleActivator.ActivateInstance(new ContainerBuilder().Build(), Enumerable.Empty <Parameter>());
         }
         builder.RegisterModule(module);
     }
     catch (Exception)
     {
         // log it
         throw;
     }
 }
        private static void ComponentRegistration_Activating(object sender, ActivatingEventArgs <object> e)
        {
            if (e.Instance == null || e.Instance.IsProxy())
            {
                return;
            }
            if (!(e.Component.Activator is ReflectionActivator ||
                  e.Component.Activator is DelegateActivator ||
                  e.Component.Activator is InstanceActivator))
            {
                return;
            }
            var limitType = e.Instance.GetType();

            if (!limitType.GetTypeInfo().CanInherited())
            {
                return;
            }
            if (excepts.Any(x => limitType.Name.Matches(x)) || excepts.Any(x => limitType.Namespace.Matches(x)))
            {
                return;
            }
            var services = e.Component.Services.Select(x => ((IServiceWithType)x).ServiceType).ToList();

            if (!services.All(x => x.GetTypeInfo().CanInherited()) || services.All(x => x.GetTypeInfo().IsNonAspect()))
            {
                return;
            }
            var aspectValidator = new AspectValidatorBuilder(e.Context.Resolve <IAspectConfiguration>()).Build();

            if (services.All(x => !aspectValidator.Validate(x, true)) && !aspectValidator.Validate(limitType, false))
            {
                return;
            }
            var  proxyTypeGenerator = e.Context.Resolve <IProxyTypeGenerator>();
            Type proxyType; object instance;
            var  interfaceType = services.FirstOrDefault(x => x.GetTypeInfo().IsInterface);

            if (interfaceType == null)
            {
                var baseType = services.FirstOrDefault(x => x.GetTypeInfo().IsClass) ?? limitType;
                proxyType = proxyTypeGenerator.CreateClassProxyType(baseType, limitType);
                var activator = new ReflectionActivator(proxyType, new DefaultConstructorFinder(type => type.GetTypeInfo().DeclaredConstructors.ToArray()), new MostParametersConstructorSelector(), new AParameter[0], new AParameter[0]);
                instance = activator.ActivateInstance(e.Context, e.Parameters);
            }
            else
            {
                proxyType = proxyTypeGenerator.CreateInterfaceProxyType(interfaceType, limitType);
                instance  = Activator.CreateInstance(proxyType, new object[] { e.Context.Resolve <IAspectActivatorFactory>(), e.Instance });
            }

            var propertyInjector = e.Context.Resolve <IPropertyInjectorFactory>().Create(instance.GetType());

            propertyInjector.Invoke(instance);
            e.Instance = instance;
            e.Component.RaiseActivating(e.Context, e.Parameters, ref instance);
        }
Exemple #8
0
        private static bool ConstructorContainsLogger(ReflectionActivator reflectionActivator)
        {
            var constructors = reflectionActivator
                               .ConstructorFinder
                               .FindConstructors(reflectionActivator.LimitType);

            return(constructors
                   .SelectMany(ctor => ctor.GetParameters())
                   .Any(parameterInfo => parameterInfo.ParameterType == typeof(ILog)));
        }
        private IComponentRegistration CreateClassInterceptorRegistration(IComponentRegistration registration)
        {
            if (registration == null)
            {
                throw new ArgumentNullException(nameof(registration));
            }

            var existingActivator          = registration.Activator as ReflectionActivator;
            var existingImplementationType = existingActivator.LimitType;

            var options = new ProxyGenerationOptions(CreateProxyGenerationHook(existingImplementationType));

            var newImplementationType = ProxyGenerator.ProxyBuilder.CreateClassProxyType(
                existingImplementationType,
                Array.Empty <Type>(),
                options);

            var newActivator = new ReflectionActivator(
                newImplementationType,
                existingActivator.ConstructorFinder,
                existingActivator.ConstructorSelector,
                Enumerable.Empty <Parameter>(),
                Enumerable.Empty <Parameter>());

            var newRegistration = new ComponentRegistration(Guid.NewGuid(), newActivator, registration.Lifetime, registration.Sharing, registration.Ownership, registration.Services, registration.Metadata, registration);

            newRegistration.Preparing += (sender, args) =>
            {
                var proxyParameters = new List <Parameter>();
                int index           = 0;

                if (options.HasMixins)
                {
                    foreach (var mixin in options.MixinData.Mixins)
                    {
                        proxyParameters.Add(new PositionalParameter(index++, mixin));
                    }
                }

                var interceptors = GetInterceptorServices(args.Component)
                                   .Select(s => args.Context.ResolveService(s))
                                   .Cast <Castle.DynamicProxy.IInterceptor>()
                                   .ToArray();
                proxyParameters.Add(new PositionalParameter(index++, interceptors));

                if (options.Selector != null)
                {
                    proxyParameters.Add(new PositionalParameter(index, options.Selector));
                }

                args.Parameters = proxyParameters.Concat(args.Parameters).ToArray();
            };

            return(newRegistration);
        }
Exemple #10
0
        static ConstructorInfo[] GetConstructorsSafe(ReflectionActivator ra)
        {
            // As of Autofac v4.7.0 "FindConstructors" will throw "NoConstructorsFoundException" instead of returning an empty array
            // See: https://github.com/autofac/Autofac/pull/895 & https://github.com/autofac/Autofac/issues/733
            ConstructorInfo[] ctors;
            try
            {
                ctors = ra.ConstructorFinder.FindConstructors(ra.LimitType);
            }
            catch (NoConstructorsFoundException)
            {
                ctors = Array.Empty <ConstructorInfo>();
            }

            return(ctors);
        }
        public static void AsInterfacesProxy <TLimit, TConcreteReflectionActivatorData, TRegistrationStyle>(this IRegistrationBuilder <TLimit, TConcreteReflectionActivatorData, TRegistrationStyle> registration)
            where TConcreteReflectionActivatorData : ConcreteReflectionActivatorData
        {
            if (registration == null)
            {
                throw new ArgumentNullException(nameof(registration));
            }

            var activatorData = registration.ActivatorData;

            var interfaceTypes = registration.RegistrationData.Services.Select(s => s.GetServiceType()).Where(type => type.IsInterface).ToArray();

            if (interfaceTypes.Length == 0)
            {
                return;
            }

            foreach (var interfaceType in interfaceTypes)
            {
                AutofacRealServiceProvider.MapActivatorData(interfaceType, activatorData);
            }

            registration.OnActivating(args =>
            {
                var parameters = args.Parameters.ToList();

                parameters.Add(new ResolvedParameter((pi, ctx) => pi.ParameterType == typeof(IServiceProvider), (pi, ctx) => ctx.Resolve <IServiceProvider>()));

                var proxyGenerator = args.Context.Resolve <IProxyGenerator>();

                var proxyType = proxyGenerator.CreateClassProxyType(activatorData.ImplementationType, activatorData.ImplementationType);

                var proxyActivator = new ReflectionActivator(proxyType, activatorData.ConstructorFinder,
                                                             activatorData.ConstructorSelector, EmptyArray <Parameter> .Value, activatorData.ConfiguredProperties);

                var proxyValue = proxyActivator.ActivateInstance(args.Context, parameters);

                args.ReplaceInstance(proxyValue);
            });
        }
        DelegateActivator BuildActivator(IComponentRegistration cr, IServiceWithType swt)
        {
            var limitType        = cr.Activator.LimitType;
            var actualDecorators = decorators
                                   .Where(d => d.Filter != null ? d.Filter(limitType) : true)
                                   .Select(d => new { Type = d.Type, Parameters = d.ParamsGetter != null ? d.ParamsGetter(limitType) : Enumerable.Empty <Parameter>() })
                                   .ToArray();

            return(new DelegateActivator(cr.Activator.LimitType, (ctx, p) =>
            {
                var typeArgs = swt.ServiceType.GetGenericArguments();
                var service = ctx.ResolveKeyed(fromKey, swt.ServiceType);
                foreach (var decorator in actualDecorators)
                {
                    var decoratorType = decorator.Type.MakeGenericType(typeArgs);
                    var @params = decorator.Parameters.Concat(new[] { new TypedParameter(swt.ServiceType, service) });
                    var activator = new ReflectionActivator(decoratorType, new DefaultConstructorFinder(), new MostParametersConstructorSelector(),
                                                            @params, Enumerable.Empty <Parameter>());
                    service = activator.ActivateInstance(ctx, @params);
                }
                return service;
            }));
        }
        /// <summary>
        /// Override to add registrations to the container.
        /// </summary>
        /// <param name="builder">The builder.</param>
        protected override void Load(ContainerBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }

            Assembly defaultAssembly = null;

            if (!string.IsNullOrEmpty(_sectionHandler.DefaultAssembly))
            {
                defaultAssembly = Assembly.Load(_sectionHandler.DefaultAssembly);
            }

            foreach (ModuleElement moduleElement in _sectionHandler.Modules)
            {
                var moduleType      = LoadType(moduleElement.Type, defaultAssembly);
                var moduleActivator = new ReflectionActivator(
                    moduleType,
                    new BindingFlagsConstructorFinder(BindingFlags.Public),
                    new MostParametersConstructorSelector(),
                    moduleElement.Parameters.ToParameters(),
                    moduleElement.Properties.ToParameters());
                var module = (IModule)moduleActivator.ActivateInstance(Container.Empty, Enumerable.Empty <Parameter>());
                builder.RegisterModule(module);
            }

            foreach (ComponentElement component in _sectionHandler.Components)
            {
                var registrar = builder.RegisterType(LoadType(component.Type, defaultAssembly));

                IList <Service> services = new List <Service>();
                if (!string.IsNullOrEmpty(component.Service))
                {
                    var serviceType = LoadType(component.Service, defaultAssembly);
                    if (!string.IsNullOrEmpty(component.Name))
                    {
                        services.Add(new KeyedService(component.Name, serviceType));
                    }
                    else
                    {
                        services.Add(new TypedService(serviceType));
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(component.Name))
                    {
                        throw new ConfigurationErrorsException(string.Format(
                                                                   ConfigurationSettingsReaderResources.ServiceTypeMustBeSpecified, component.Name));
                    }
                }

                foreach (ServiceElement service in component.Services)
                {
                    var serviceType = LoadType(service.Type, defaultAssembly);
                    if (!string.IsNullOrEmpty(service.Name))
                    {
                        services.Add(new KeyedService(service.Name, serviceType));
                    }
                    else
                    {
                        services.Add(new TypedService(serviceType));
                    }
                }

                foreach (var service in services)
                {
                    registrar.As(service);
                }

                foreach (var param in component.Parameters.ToParameters())
                {
                    registrar.WithParameter(param);
                }

                foreach (var prop in component.Properties.ToParameters())
                {
                    registrar.WithProperty(prop);
                }

                foreach (var ep in component.Metadata)
                {
                    registrar.WithMetadata(
                        ep.Name, TypeManipulation.ChangeToCompatibleType(ep.Value, Type.GetType(ep.Type)));
                }

                if (!string.IsNullOrEmpty(component.MemberOf))
                {
                    registrar.MemberOf(component.MemberOf);
                }

                SetScope(component, registrar);
                SetOwnership(component, registrar);
                SetInjectProperties(component, registrar);
            }

            foreach (FileElement file in _sectionHandler.Files)
            {
                var section = DefaultSectionName;
                if (!string.IsNullOrEmpty(file.Section))
                {
                    section = file.Section;
                }

                var reader = new ConfigurationSettingsReader(section, file.Name);
                builder.RegisterModule(reader);
            }
        }
Exemple #14
0
 static bool AnyConstructorHasLoggerDependency(ReflectionActivator activator)
 => activator
 .ConstructorFinder.FindConstructors(activator.LimitType)
 .SelectMany(constructor => constructor.GetParameters().Select(_ => _.ParameterType))
 .Any(parameterType => parameterType == typeof(ILogger));