protected override void AttachToComponentRegistration(IComponentRegistryBuilder componentRegistry, IComponentRegistration registration)
        {
            // ignore components that provide loggers
            if (registration.Services.OfType <TypedService>().Any(ts => ts.ServiceType.IsAssignableTo <ILogger>()))
            {
                return;
            }

            if (registration.Activator is ReflectionActivator ra)
            {
                var parameters = ra.ConstructorFinder
                                 .FindConstructors(ra.LimitType)
                                 .SelectMany(ctor => ctor.GetParameters());

                if (parameters.Any(pi => pi.ParameterType == typeof(ILogger)))
                {
                    registration.PipelineBuilding += (sender, args) =>
                    {
                        args.Use(global::Autofac.Core.Resolving.Pipeline.PipelinePhase.ParameterSelection, (context, next) =>
                        {
                            var logger = context.Resolve <ILoggerFactory>().CreateLogger(registration.Activator.LimitType);
                            context.ChangeParameters(context.Parameters.Append(TypedParameter.From(logger)));
                            next(context);
                        });
                    };
                }
            }
        }
Exemple #2
0
 protected override void AttachToComponentRegistration(
     IComponentRegistryBuilder componentRegistry,
     IComponentRegistration registration)
 {
     // Any time a component is resolved, it goes through Preparing
     registration.Preparing += InjectLangParameter;
 }
Exemple #3
0
 /// <inheritdoc/>
 protected override void AttachToComponentRegistration(IComponentRegistryBuilder registry,
                                                       IComponentRegistration registration)
 {
     // Ignore components that provide loggers (and thus avoid a circular dependency below)
     if (registration.Services
         .OfType <TypedService>()
         .Any(ts => ts.ServiceType == typeof(ILogger) ||
              ts.ServiceType == typeof(ILoggerProvider)))
     {
         return;
     }
     if (registration.Activator is ReflectionActivator ra)
     {
         try {
             var ctors      = ra.ConstructorFinder.FindConstructors(ra.LimitType);
             var usesLogger = ctors
                              .SelectMany(ctor => ctor.GetParameters())
                              .Any(pi => pi.ParameterType == typeof(ILogger));
             // Ignore components known to be without logger dependencies
             if (!usesLogger)
             {
                 return;
             }
         }
         catch (NoConstructorsFoundException) {
             return; // No need
         }
     }
     registration.Preparing += (sender, args) => {
         var log = args.Context.Resolve <ILogger>().ForContext(registration.Activator.LimitType);
         args.Parameters = new[] { TypedParameter.From(log) }.Concat(args.Parameters);
     };
 }
 protected override void AttachToComponentRegistration(
     IComponentRegistryBuilder componentRegistry,
     IComponentRegistration registration)
 {
     base.AttachToComponentRegistration(componentRegistry, registration);
     registration.PipelineBuilding += RegistrationOnPipelineBuilding;
 }
        protected override void AttachToComponentRegistration(IComponentRegistryBuilder componentRegistry, IComponentRegistration registration)
        {
            _ = registration ?? throw new ArgumentNullException(nameof(registration));

            base.AttachToComponentRegistration(componentRegistry, registration);

            if (registration.Activator.LimitType == typeof(TService))
            {
                registration.PipelineBuilding += (sender, pipeline) =>
                {
                    pipeline.Use(
                        PipelinePhase.ParameterSelection,
                        (context, next) =>
                    {
                        context.ChangeParameters(
                            context.Parameters.Union(
                                new[]
                        {
                            new ResolvedParameter(
                                (p, i) => p.ParameterType == typeof(HttpClient),
                                (p, i) =>
                            {
                                var client = i.Resolve <IHttpClientFactory>().CreateClient();
                                _clientConfigurator?.Invoke(client);
                                return(client);
                            })
                        }));
                        next(context);
                    });
                };
            }
        }
        private static void ScanTypesTemplate <TActivatorData, TScanStyle, TRegistrationBuilderStyle>(
            IEnumerable <Type> types,
            IComponentRegistryBuilder cr,
            IRegistrationBuilder <object, BaseScanningActivatorData <TActivatorData, TScanStyle>, TRegistrationBuilderStyle> rb,
            Func <Type, IRegistrationBuilder <object, TActivatorData, TScanStyle> > scannedConstructorFunc,
            Action <IComponentRegistryBuilder, IRegistrationBuilder <object, TActivatorData, TScanStyle> > register)
            where TActivatorData : ReflectionActivatorData
        {
            foreach (var t in types)
            {
                var scanned = scannedConstructorFunc(t);

                scanned.ConfigureFrom(rb, t);

                if (scanned.RegistrationData.Services.Any())
                {
                    register(cr, scanned);
                }
            }

            foreach (var postScanningCallback in rb.ActivatorData.PostScanningCallbacks)
            {
                postScanningCallback(cr);
            }
        }
Exemple #7
0
        protected override void AttachToComponentRegistration(IComponentRegistryBuilder componentRegistryBuilder, IComponentRegistration registration)
        {
            //处理构造函数的参数
            registration.Preparing += OnComponentPreparing;

            //处理属性
            registration.Activated += (sender, e) => InjectLoggerProperties(e.Instance);
        }
Exemple #8
0
        protected override void AttachToComponentRegistration(IComponentRegistryBuilder componentRegistryBuilder, IComponentRegistration registration)
        {
            // Handle constructor parameters.
            registration.Preparing += OnComponentPreparing;

            // Handle properties.
            registration.Activated += (sender, e) => InjectLoggerProperties(e.Instance);
        }
Exemple #9
0
 /// <summary>
 /// Configure an existing registry with the component registrations
 /// that have been made. Primarily useful in dynamically adding registrations
 /// to a child lifetime scope.
 /// </summary>
 /// <remarks>
 /// Update can only be called once per <see cref="ContainerBuilder"/>
 /// - this prevents ownership issues for provided instances.
 /// </remarks>
 /// <param name="componentRegistry">An existing registry to make the registrations in.</param>
 internal void UpdateRegistry(IComponentRegistryBuilder componentRegistry)
 {
     if (componentRegistry == null)
     {
         throw new ArgumentNullException(nameof(componentRegistry));
     }
     Build(componentRegistry, true);
 }
 protected override void AttachToComponentRegistration(IComponentRegistryBuilder componentRegistry, IComponentRegistration registration)
 {
     registration.PipelineBuilding += (sender, pipeline) =>
     {
         pipeline.Use(_middleware);
     };
     base.AttachToComponentRegistration(componentRegistry, registration);
 }
Exemple #11
0
        /// <summary>
        /// Initializes a new instance.
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="cache"></param>
        /// <param name="lifetimeScopeTagForSingletons"></param>
        public ComponentRegistryServiceCollection(IComponentRegistryBuilder builder, ComponentRegistryServiceCollectionCache cache, object lifetimeScopeTagForSingletons)
        {
            this.builder = builder ?? throw new ArgumentNullException(nameof(builder));
            this.cache   = cache ?? throw new ArgumentNullException(nameof(cache));
            this.lifetimeScopeTagForSingletons = lifetimeScopeTagForSingletons;

            builder.Registered += builder_Registered;
        }
        //public  Log4NetMiddleware middleware { get; set; }

        //public MiddlewareModule(IResolveMiddleware middleware)
        //{
        //    this.middleware = middleware;
        //}

        protected override void AttachToComponentRegistration(IComponentRegistryBuilder componentRegistryBuilder, IComponentRegistration registration)
        {
            // Attach to the registration's pipeline build.
            registration.PipelineBuilding += (sender, pipeline) =>
            {
                // Add our middleware to the pipeline.
                pipeline.Use(new Log4NetMiddleware());
            };
        }
Exemple #13
0
        protected override void AttachToComponentRegistration(IComponentRegistryBuilder componentRegistry, IComponentRegistration registration)
        {
            //// Ignore components that provide loggers (and thus avoid a circular dependency below)
            //if (registration.Services.OfType<TypedService>().Any(ts => ts.ServiceType == typeof(ILogger)))
            //    return;

            bool hasCtorLogger     = false;
            bool hasPropertyLogger = false;

            FastProperty[] loggerProperties = null;

            var ra = registration.Activator as ReflectionActivator;

            if (ra != null)
            {
                // // Look for ctor parameters of type "ILogger"
                var ctors            = GetConstructorsSafe(ra);
                var loggerParameters = ctors.SelectMany(ctor => ctor.GetParameters()).Where(pi => pi.ParameterType == typeof(ILogger));
                hasCtorLogger = loggerParameters.Any();

                // Autowire properties
                // Look for settable properties of type "ILogger"
                loggerProperties = ra.LimitType
                                   .GetProperties(BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance)
                                   .Select(p => new
                {
                    PropertyInfo = p,
                    p.PropertyType,
                    IndexParameters = p.GetIndexParameters(),
                    Accessors       = p.GetAccessors(false)
                })
                                   .Where(x => x.PropertyType == typeof(ILogger))                                    // must be a logger
                                   .Where(x => x.IndexParameters.Count() == 0)                                       // must not be an indexer
                                   .Where(x => x.Accessors.Length != 1 || x.Accessors[0].ReturnType == typeof(void)) //must have get/set, or only set
                                   .Select(x => FastProperty.Create(x.PropertyInfo))
                                   .ToArray();

                hasPropertyLogger = loggerProperties.Length > 0;

                // Ignore components known to be without logger dependencies
                if (!hasCtorLogger && !hasPropertyLogger)
                {
                    return;
                }

                if (hasPropertyLogger)
                {
                    registration.Metadata.Add("LoggerProperties", loggerProperties);
                }
            }

            registration.PipelineBuilding += (sender, pipeline) =>
            {
                // Add our middleware to the pipeline.
                pipeline.Use(new AutofacSerilogMiddleware(registration.Activator.LimitType, hasCtorLogger, hasPropertyLogger));
            };
        }
Exemple #14
0
 protected override void AttachToComponentRegistration(IComponentRegistryBuilder componentRegistry, IComponentRegistration registration)
 {
     registration.ConfigurePipeline(builder => builder.Use(PipelinePhase.Activation, (ctxt, next) =>
     {
         ctxt.Instance = new ReplaceableComponent {
             IsReplaced = true
         };
     }));
 }
Exemple #15
0
 protected override void AttachToComponentRegistration(IComponentRegistryBuilder componentRegistry, IComponentRegistration registration)
 {
     registration.Activating += (o, args) =>
     {
         args.ReplaceInstance(new ReplaceableComponent {
             IsReplaced = true
         });
     };
 }
Exemple #16
0
        protected override void AttachToComponentRegistration(IComponentRegistryBuilder componentRegistry, IComponentRegistration registration)
#endif
        {
            // Deals with constructor injection
            registration.Preparing += AddAutoLazyResolvedParameter;

            if(handlePropertyInjection)
                registration.Activated += AssignAutoLazyInstanceToAllApplicableProperties;
        }
Exemple #17
0
 private void AttachToSources(IComponentRegistryBuilder componentRegistry)
 {
     if (componentRegistry == null)
     {
         throw new ArgumentNullException(nameof(componentRegistry));
     }
     componentRegistry.RegistrationSourceAdded +=
         (sender, e) => AttachToRegistrationSource(e.ComponentRegistry, e.RegistrationSource);
 }
Exemple #18
0
        public void LoadsRegistrations()
        {
            IComponentRegistryBuilder builder = Factory.CreateEmptyComponentRegistryBuilder();

            new ObjectModule().Configure(builder);
            var registry = builder.Build();

            Assert.True(registry.IsRegistered(new TypedService(typeof(object))));
        }
Exemple #19
0
 private void AttachToRegistrations(IComponentRegistryBuilder componentRegistry)
 {
     if (componentRegistry == null)
     {
         throw new ArgumentNullException(nameof(componentRegistry));
     }
     componentRegistry.Registered +=
         (sender, e) => AttachToComponentRegistration(e.ComponentRegistryBuilder, e.ComponentRegistration);
 }
        protected override void AttachToComponentRegistration(IComponentRegistryBuilder componentRegistry, IComponentRegistration registration)
        {
            if (registration == null)
            {
                throw new ArgumentNullException("registration");
            }

            registration.PipelineBuilding += RegistrationPipelineBuilding;
        }
 internal MutableContainer(ContainerBuilder builder)
 {
     builder.RegisterInstance(this).As <IMutableContainer>().As <IContainer>().SingleInstance();
     _container               = builder.Build();
     _componentRegistration   = builder.ComponentRegistryBuilder;
     _additionalRegistrations = new List <IContainer>();
     _lifetimeScope           = _container.Resolve <ILifetimeScope>();
     _lifetimeScope.ChildLifetimeScopeBeginning += OnChildLifetimeScopeBeginning;
     _lifetimeScope.CurrentScopeEnding          += OnCurrentScopeEnding;
     _lifetimeScope.ResolveOperationBeginning   += OnResolveOperationBeginning;
 }
Exemple #22
0
 private void RegisterDefaultAdapters(IComponentRegistryBuilder componentRegistry)
 {
     this.RegisterGeneric(typeof(KeyedServiceIndex <,>)).As(typeof(IIndex <,>)).InstancePerLifetimeScope();
     componentRegistry.AddRegistrationSource(new CollectionRegistrationSource());
     componentRegistry.AddRegistrationSource(new OwnedInstanceRegistrationSource());
     componentRegistry.AddRegistrationSource(new MetaRegistrationSource());
     componentRegistry.AddRegistrationSource(new LazyRegistrationSource());
     componentRegistry.AddRegistrationSource(new LazyWithMetadataRegistrationSource());
     componentRegistry.AddRegistrationSource(new StronglyTypedMetaRegistrationSource());
     componentRegistry.AddRegistrationSource(new GeneratedFactoryRegistrationSource());
 }
        protected override void AttachToComponentRegistration(IComponentRegistryBuilder componentRegistry, IComponentRegistration registration)
        {
            if (!DataSettings.DatabaseIsInstalled())
            {
                return;
            }

            var userProperty = FindUserProperty(registration.Activator.LimitType);

            if (userProperty == null)
            {
                return;
            }

            registration.Metadata.Add("Property.T", FastProperty.Create(userProperty));

            registration.PipelineBuilding += (sender, pipeline) =>
            {
                // Add our Localizer middleware to the pipeline.
                pipeline.Use(PipelinePhase.ParameterSelection, (context, next) =>
                {
                    next(context);

                    if (!context.Resolve <IEngine>().IsInitialized)
                    {
                        return;
                    }

                    if (!context.NewInstanceActivated || context.Registration.Metadata.Get("Property.T") is not FastProperty prop)
                    {
                        return;
                    }

                    try
                    {
                        var iText = context.Resolve <IText>();
                        if (prop.Property.PropertyType == typeof(Localizer))
                        {
                            Localizer localizer = context.Resolve <IText>().Get;
                            prop.SetValue(context.Instance, localizer);
                        }
                        else
                        {
                            LocalizerEx localizerEx = context.Resolve <IText>().GetEx;
                            prop.SetValue(context.Instance, localizerEx);
                        }
                    }
                    catch { }
                });
            };
        /// <summary>
        /// Initializes a new instance of the <see cref="ComponentRegisteredEventArgs"/> class.
        /// </summary>
        /// <param name="registryBuilder">The <see cref="IComponentRegistryBuilder" /> into which the registration was made.</param>
        /// <param name="componentRegistration">The component registration.</param>
        public ComponentRegisteredEventArgs(IComponentRegistryBuilder registryBuilder, IComponentRegistration componentRegistration)
        {
            if (registryBuilder == null)
            {
                throw new ArgumentNullException(nameof(registryBuilder));
            }
            if (componentRegistration == null)
            {
                throw new ArgumentNullException(nameof(componentRegistration));
            }

            ComponentRegistryBuilder = registryBuilder;
            ComponentRegistration    = componentRegistration;
        }
Exemple #25
0
    /// <inheritdoc />
    protected override void AttachToComponentRegistration(IComponentRegistryBuilder componentRegistry, IComponentRegistration registration)
    {
        if (registration.Activator is not ReflectionActivator reflectionActivator)
        {
            return;
        }

        if (!AnyConstructorHasLoggerDependency(reflectionActivator))
        {
            return;
        }

        registration.PipelineBuilding += (_, builder) => builder.Use(new LoggerResolvingMiddleware(reflectionActivator.LimitType));
    }
Exemple #26
0
        /// <summary>
        /// Apply the module to the component registry.
        /// </summary>
        /// <param name="componentRegistry">Component registry to apply configuration to.</param>
        public void Configure(IComponentRegistryBuilder componentRegistry)
        {
            if (componentRegistry == null)
            {
                throw new ArgumentNullException(nameof(componentRegistry));
            }

            var moduleBuilder = new ContainerBuilder(componentRegistry.Properties);

            Load(moduleBuilder);
            moduleBuilder.UpdateRegistry(componentRegistry);
            AttachToRegistrations(componentRegistry);
            AttachToSources(componentRegistry);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="RegistrationSourceAddedEventArgs"/> class.
        /// </summary>
        /// <param name="componentRegistry">The registry to which the source was added.</param>
        /// <param name="registrationSource">The source that was added.</param>
        /// <exception cref="ArgumentNullException"></exception>
        public RegistrationSourceAddedEventArgs(IComponentRegistryBuilder componentRegistry, IRegistrationSource registrationSource)
        {
            if (componentRegistry == null)
            {
                throw new ArgumentNullException(nameof(componentRegistry));
            }
            if (registrationSource == null)
            {
                throw new ArgumentNullException(nameof(registrationSource));
            }

            ComponentRegistry  = componentRegistry;
            RegistrationSource = registrationSource;
        }
        /// <summary>
        /// Override to attach module-specific functionality to a
        /// component registration.
        /// </summary>
        /// <remarks>This method will be called for all existing <i>and future</i> component
        /// registrations - ordering is not important.</remarks>
        /// <param name="componentRegistry">The component registry builder.</param>
        /// <param name="registration">The registration to attach functionality to.</param>
        protected override void AttachToComponentRegistration(IComponentRegistryBuilder componentRegistry, IComponentRegistration registration)
        {
            if (registration == null)
            {
                throw new ArgumentNullException(nameof(registration));
            }

            foreach (var property in MetadataHelper.GetMetadata(registration.Activator.LimitType))
            {
                if (!registration.Metadata.ContainsKey(property.Key))
                {
                    registration.Metadata.Add(property);
                }
            }
        }
Exemple #29
0
        private static void AttachExport(IComponentRegistryBuilder registry, IComponentRegistration registration, ExportConfigurationBuilder exportConfiguration)
        {
            var contractService = new ContractBasedService(exportConfiguration.ContractName, exportConfiguration.ExportTypeIdentity);

            var rb = RegistrationBuilder.ForDelegate((c, p) =>
            {
                var ctx = c.Resolve <IComponentContext>();
                return(new Export(
                           new ExportDefinition(exportConfiguration.ContractName, exportConfiguration.Metadata),
                           () => ctx.ResolveComponent(new ResolveRequest(contractService, registration, Array.Empty <Parameter>()))));
            })
                     .As(contractService)
                     .ExternallyOwned()
                     .WithMetadata((IEnumerable <KeyValuePair <string, object> >)exportConfiguration.Metadata);

            registry.Register(rb.CreateRegistration());
        }
Exemple #30
0
        private static void ScanTypes(IEnumerable <Type> types, IComponentRegistryBuilder cr, IRegistrationBuilder <object, ScanningActivatorData, DynamicRegistrationStyle> rb)
        {
            rb.ActivatorData.Filters.Add(t =>
                                         rb.RegistrationData.Services.OfType <IServiceWithType>().All(swt =>
                                                                                                      swt.ServiceType.IsAssignableFrom(t)));

            // Issue #897: For back compat reasons we can't filter out
            // non-public types here. Folks use assembly scanning on their
            // own stuff, so encapsulation is a tricky thing to manage.
            // If people want only public types, a LINQ Where clause can be used.
            foreach (var t in types
                     .Where(t =>
                            t.IsClass &&
                            !t.IsAbstract &&
                            !t.IsGenericTypeDefinition &&
                            !t.IsDelegate() &&
                            rb.ActivatorData.Filters.All(p => p(t)) &&
                            !t.IsCompilerGenerated()))
            {
                var scanned = RegistrationBuilder.ForType(t)
                              .FindConstructorsWith(rb.ActivatorData.ConstructorFinder)
                              .UsingConstructor(rb.ActivatorData.ConstructorSelector)
                              .WithParameters(rb.ActivatorData.ConfiguredParameters)
                              .WithProperties(rb.ActivatorData.ConfiguredProperties);

                // Copy middleware from the scanning registration.
                scanned.ResolvePipeline.UseRange(rb.ResolvePipeline.Middleware);

                scanned.RegistrationData.CopyFrom(rb.RegistrationData, false);

                foreach (var action in rb.ActivatorData.ConfigurationActions)
                {
                    action(t, scanned);
                }

                if (scanned.RegistrationData.Services.Any())
                {
                    RegistrationBuilder.RegisterSingleComponent(cr, scanned);
                }
            }

            foreach (var postScanningCallback in rb.ActivatorData.PostScanningCallbacks)
            {
                postScanningCallback(cr);
            }
        }