protected override void AttachToComponentRegistration( IComponentRegistry componentRegistry, IComponentRegistration registration) { registration.Preparing += (sender, args) => log.Debug($@"Resolving concrete type {args.Component.Activator.LimitType}"); }
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { var type = registration.Activator.LimitType; // AF2.0+ // .Descriptor.BestKnownImplementationType; // AF1.2+ // we hook preparing to inject the logger into the constructor registration.Preparing += OnComponentPreparing; // build the list of actions for type and assign loggers to properties var injectors = BuildLogPropertyInjectors(type); // no logger properties, no need to hook up the event // ReSharper disable PossibleMultipleEnumeration if (!injectors.Any()) // ReSharper restore PossibleMultipleEnumeration return; // we hook acticating to inject the logger into the known public properties registration.Activating += (s, e) => { // ReSharper disable PossibleMultipleEnumeration foreach (var injector in injectors) // ReSharper restore PossibleMultipleEnumeration injector(e.Context, e.Instance); }; }
public ShapeAttributeOccurrence(ShapeAttribute shapeAttribute, MethodInfo methodInfo, IComponentRegistration registration, Func<Feature> feature) { ShapeAttribute = shapeAttribute; MethodInfo = methodInfo; Registration = registration; _feature = feature; }
public InstanceLookup( IComponentRegistration registration, IResolveOperation context, ISharingLifetimeScope mostNestedVisibleScope, IEnumerable<Parameter> parameters) { Parameters = parameters; ComponentRegistration = registration; _context = context; try { _activationScope = ComponentRegistration.Lifetime.FindScope(mostNestedVisibleScope); } catch (DependencyResolutionException ex) { var services = new StringBuilder(); foreach (var s in registration.Services) { services.Append("- "); services.AppendLine(s.Description); } var message = String.Format(CultureInfo.CurrentCulture, ComponentActivationResources.UnableToLocateLifetimeScope, registration.Activator.LimitType, services); throw new DependencyResolutionException(message, ex); } }
protected override void AttachToComponentRegistration(IComponentRegistry registry, IComponentRegistration registration) { registration.Preparing += (s, e) => { e.Parameters = new [] { loggerParameter }.Concat(e.Parameters); }; }
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { registration.Preparing += RegistrationOnPreparing; registration.Activating += RegistrationOnActivating; base.AttachToComponentRegistration(componentRegistry, registration); }
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { registration.Preparing += (sender, args) => { args.Parameters = args.Parameters.Union( new[] { new NamedParameter(@"basePoint", _basePoint) } ); }; }
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { var implementationType = registration.Activator.LimitType; foreach (var autoWireType in autoWireTypes) { var constructors = implementationType.GetConstructorsWithDependency(autoWireType); if (constructors.Any()) { registration.Preparing += (sender, e) => { var parameter = new TypedParameter(autoWireType, e.Context.Resolve(autoWireType, new TypedParameter(typeof(Type), implementationType))); e.Parameters = e.Parameters.Concat(new[] { parameter }); }; } else { var props = implementationType.GetPropertiesWithDependency(autoWireType); if (props.Any()) { registration.Activated += (s, e) => { foreach (var prop in props) { prop.SetValue(e.Instance, e.Context.Resolve(autoWireType)); } }; } } } foreach (var serviceType in typebasedServiceTypes) { var constructorInjectors = BuildConstructorServiceInjectors(implementationType, serviceType).ToArray(); if (constructorInjectors.Any()) { registration.Preparing += (s, e) => { foreach (var ci in constructorInjectors) ci(e); }; return; } // build an array of actions on this type to assign loggers to member properties var injectors = BuildPropertyServiceInjectors(implementationType, serviceType).ToArray(); if (injectors.Any()) { registration.Activated += (s, e) => { foreach (var injector in injectors) injector(e.Context, e.Instance); }; } } }
/// <summary> /// Initializes a new instance of the <see cref="PreparingEventArgs"/> class. /// </summary> /// <param name="service">Service which is preparing</param> /// <param name="context">The context.</param> /// <param name="component">The component.</param> /// <param name="parameters">The parameters.</param> public PreparingEventArgs(Service service, IComponentContext context, IComponentRegistration component, IEnumerable<Parameter> parameters) { _service = Enforce.ArgumentNotNull(service, "service"); _context = Enforce.ArgumentNotNull(context, "context"); _component = Enforce.ArgumentNotNull(component, "component"); _parameters = Enforce.ArgumentNotNull(parameters, "parameters"); }
/// <summary> /// Initializes a new instance of the <see cref="ProxyPart"/> class. /// </summary> /// <param name="registration">The registration</param> /// <param name="innerPart">The inner part.</param> public ProxyPart(ComponentRegistrationBase registration, ComposablePart innerPart) { implementation = GetImplementation(registration); this.registration = registration; this.innerPart = innerPart; DeterminePropertiesToInject(); }
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { registration.Activating += (sender, e) => { if (typeof (IMessageConsumer).IsAssignableFrom(e.Instance.GetType())) consumerInterceptor.ItemCreated(e.Instance.GetType(), e.Component.Lifetime.GetType().Equals(typeof(CurrentScopeLifetime))); }; }
public ComponentRegistrationLifetimeDecorator(IComponentRegistration inner, IComponentLifetime lifetime) { if (inner == null) throw new ArgumentNullException("inner"); if (lifetime == null) throw new ArgumentNullException("lifetime"); _inner = inner; _lifetime = lifetime; }
static IEnumerable<Parameter> AddDecoratedComponentParameter(Type decoratedParameterType, IComponentRegistration decoratedComponent, IEnumerable<Parameter> configuredParameters) { var parameter = new ResolvedParameter( (pi, c) => pi.ParameterType == decoratedParameterType, (pi, c) => c.ResolveComponent(decoratedComponent, Enumerable.Empty<Parameter>())); return new[] { parameter }.Concat(configuredParameters); }
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { // Handle constructor parameters. registration.Preparing += OnComponentPreparing; // Handle properties. registration.Activated += (sender, e) => InjectLoggerProperties(e.Instance); }
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { registration.Preparing += (sender, args) => args.Parameters = args.Parameters.Concat(new[] { new ResolvedParameter((info, context) => info.ParameterType == typeof (ILog), (info, context) => _logFactory(info.Member.DeclaringType)) }); }
/// <summary> /// Initializes a new instance of the <see cref="ComponentRegisteredEventArgs"/> class. /// </summary> /// <param name="registry">The container into which the registration /// was made.</param> /// <param name="componentRegistration">The component registration.</param> public ComponentRegisteredEventArgs(IComponentRegistry registry, IComponentRegistration componentRegistration) { if (registry == null) throw new ArgumentNullException(nameof(registry)); if (componentRegistration == null) throw new ArgumentNullException(nameof(componentRegistration)); ComponentRegistry = registry; ComponentRegistration = componentRegistration; }
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { // Use the event args to log detailed info registration.Preparing += (sender, args) => Debug.WriteLine( "Resolving concrete type {0}, Id {1}", args.Component.Activator.LimitType, args.Component.Id.ToString()); }
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { Type implementationType = registration.Activator.LimitType; if (DynamicProxyContext.From(registration) != null && implementationType.FullName == "Orchard.Car.Services.CarInfoService") { registration.InterceptedBy<SimpleInterceptor>(); } }
public void RecordActivation(IComponentRegistration component) { lock (_synchRoot) { var componentInfo = GetComponent(component.Id); componentInfo.RecordActivation(); } }
/// <summary> /// Attempts to find a default registration for the specified service. /// </summary> /// <param name="service">The service to look up.</param> /// <param name="registration">The default registration for the service.</param> /// <returns>True if a registration exists.</returns> public bool TryGetRegistration(Service service, out IComponentRegistration registration) { if (service == null) throw new ArgumentNullException("service"); lock (_synchRoot) { var info = GetInitializedServiceInfo(service); return info.TryGetRegistration(out registration); } }
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { base.AttachToComponentRegistration(componentRegistry, registration); if (registration.Activator.LimitType.IsAssignableTo<IHandle>()) { registration.Activated += RegistrationOnActivated; } }
public ProfilingActivator( IComponentRegistration registration, IInstanceActivator innerActivator, ContainerProfile profile) { _registration = registration; _innerActivator = innerActivator; _profile = profile; }
protected override void AttachToComponentRegistration( IContainer container, IComponentRegistration registration) { base.AttachToComponentRegistration(container, registration); var registeredType = registration.Descriptor.BestKnownImplementationType; if (IsConfiguredTransport(registeredType)) DecorateTransport(container, registeredType); }
/// <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.</param> /// <param name="registration">The registration to attach functionality to.</param> protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { if (registration == null) { throw new ArgumentNullException("registration"); } foreach (var property in MetadataHelper.GetMetadata(registration.Activator.LimitType)) registration.Metadata.Add(property); }
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { if (!registration.Services.Contains(new TypedService(typeof(ICommandHandler)))) return; var builder = new CommandHandlerDescriptorBuilder(); var descriptor = builder.Build(registration.Activator.LimitType); registration.Metadata.Add(typeof(CommandHandlerDescriptor).FullName, descriptor); }
private ServiceHost CreateServiceHost(IWorkContextAccessor workContextAccessor, IComponentRegistration registration, Type implementationType, Uri[] baseAddresses) { ServiceHost host = CreateServiceHost(implementationType, baseAddresses); host.Opening += delegate { host.Description.Behaviors.Add(new OrchardDependencyInjectionServiceBehavior(workContextAccessor, implementationType, registration)); }; return host; }
public override void Register(IComponentRegistration registration, bool preserveDefaults) { var toRegister = registration; if (registration.Lifetime is RootScopeLifetime) toRegister = new ComponentRegistrationLifetimeDecorator(registration, _restrictedRootScopeLifetime); base.Register(toRegister, preserveDefaults); }
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { var implementationType = registration.Activator.LimitType; var property = FindProperty(implementationType); if (property != null) { registration.InterceptedBy<ISecurityModuleInterceptor>(); } }
public IEnumerable<ParameterInfo> GetRegistrationCtorParameters(IComponentRegistration componentRegistration) { var activator = componentRegistration.Activator as ReflectionActivator; if (activator == null) return Enumerable.Empty<ParameterInfo>(); var limitType = activator.LimitType; return activator.ConstructorFinder.FindConstructors(limitType).SelectMany(ctor => ctor.GetParameters()); }
public DependencyTrackingContext( ContainerProfile profile, IComponentRegistration registration, IComponentContext context) { _profile = profile; _registration = registration; _context = context; }
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { var userProperty = FindUserProperty(registration.Activator.LimitType); if (userProperty != null) { var scope = registration.Activator.LimitType.FullName; registration.Activated += (sender, e) => { var localizer = _localizerCache.GetOrAdd(scope, key => LocalizationUtilities.Resolve(e.Context, scope)); userProperty.SetValue(e.Instance, localizer, null); }; } }
protected IEnumerable <Type> GetGenericFactoryTypes(IComponentRegistration componentRegistration) { return(from ctorParameter in GetRegistrationCtorParameters(componentRegistration) where ctorParameter.ParameterType.FullName.StartsWith("System.Func") select ctorParameter.ParameterType.GetGenericArguments()[0]); }
public ComponentRegisteredEventArgs(IComponentRegistry registry, IComponentRegistration componentRegistration) { this._componentRegistry = Enforce.ArgumentNotNull <IComponentRegistry>(registry, "registry"); this._componentRegistration = Enforce.ArgumentNotNull <IComponentRegistration>(componentRegistration, "componentRegistration"); }
protected override void AttachToComponentRegistration(IComponentRegistry registry, IComponentRegistration registration) { registration.Activated += EventAggregationAutoSubscriptionModule.OnComponentActivated; }
public void Stop(IKernel kernel, IComponentRegistration registration) { invokeMethod("Stop", kernel, registration); }
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { if (registration.Activator.LimitType == typeof(ProxDependency)) { registration.InterceptedBy <ProxIntercept>(); } }
protected virtual void ConfigureConsumer(IComponentRegistration registration) { }
public object ResolveComponent(IComponentRegistration registration, IEnumerable <Parameter> parameters) { return(realScope.ResolveComponent(registration, parameters)); }
private ServiceHost CreateServiceHost(IWorkContextAccessor workContextAccessor, IComponentRegistration registration, Type implementationType, Uri[] baseAddresses) { ServiceHost host = CreateServiceHost(implementationType, baseAddresses); host.Opening += delegate { host.Description.Behaviors.Add(new TomeltDependencyInjectionServiceBehavior(workContextAccessor, implementationType, registration)); }; return(host); }
private static IComponentRegistration CreateMetaRegistration <T>(Service providedService, IComponentRegistration valueRegistration) { var rb = RegistrationBuilder .ForDelegate((c, p) => new Meta <T>( (T)c.ResolveComponent(valueRegistration, p), valueRegistration.Target.Metadata)) .As(providedService) .Targeting(valueRegistration) .InheritRegistrationOrderFrom(valueRegistration); return(rb.CreateRegistration()); }
/// <summary> /// Resolve an instance of the provided registration within the context. /// </summary> /// <param name="registration">The registration.</param> /// <param name="parameters">Parameters for the instance.</param> /// <returns> /// The component instance. /// </returns> /// <exception cref="ComponentNotRegisteredException"/> /// <exception cref="DependencyResolutionException"/> public object ResolveComponent(IComponentRegistration registration, IEnumerable <Parameter> parameters) { return(GetOrCreateInstance(_mostNestedLifetimeScope, registration, parameters)); }
public RegisteredEventArgs(IKernel kernel, IComponentRegistration registration) { _kernel = kernel; _registration = registration; }
public ActivatedEventArgs(ICreationContext context, IComponentRegistration component, object instance) { Context = context; Component = component; Instance = instance; }
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { registration.Metadata["Hello"] = "World"; }
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.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> /// Lazy registration creator called via reflection by the source /// to generate a <see cref="Lazy{T, TMetadata}"/> component. /// </summary> /// <typeparam name="T">The type of service being resolved.</typeparam> /// <typeparam name="TMetadata">The type of metadata object associated with the service.</typeparam> /// <param name="providedService">The service for which the component registration is being generated.</param> /// <param name="valueRegistration">The registration that should provide the component value.</param> /// <returns> /// An <see cref="IComponentRegistration"/> containing a <see cref="Lazy{T, TMetadata}"/>. /// </returns> private static IComponentRegistration CreateLazyRegistration <T, TMetadata>(Service providedService, IComponentRegistration valueRegistration) { var rb = RegistrationBuilder.ForDelegate( (c, p) => { var context = c.Resolve <IComponentContext>(); return(new Lazy <T, TMetadata>( () => (T)context.ResolveComponent(new ResolveRequest(providedService, valueRegistration, p)), AttributedModelServices.GetMetadataView <TMetadata>(valueRegistration.Target.Metadata))); }) .As(providedService) .Targeting(valueRegistration, true); return(rb.CreateRegistration()); }
public bool ShouldRecalculateAdaptersOn(IComponentRegistration registration) { return(this.IsInitialized); }
private static IComponentRegistration CreateLazyRegistration <T>(Service providedService, IComponentRegistration valueRegistration) { var rb = RegistrationBuilder.ForDelegate( (c, p) => { var context = c.Resolve <IComponentContext>(); return(new Lazy <T>(() => (T)context.ResolveComponent(valueRegistration, p))); }) .As(providedService) .Targeting(valueRegistration) .InheritRegistrationOrderFrom(valueRegistration); return(rb.CreateRegistration()); }
private static IComponentRegistration CreateLazyRegistration <T, TMeta>(Service providedService, IComponentRegistration valueRegistration) { var metadataProvider = MetadataViewProvider.GetMetadataViewProvider <TMeta>(); var metadata = metadataProvider(valueRegistration.Target.Metadata); var rb = RegistrationBuilder.ForDelegate( (c, p) => { var context = c.Resolve <IComponentContext>(); var lazyType = ((IServiceWithType)providedService).ServiceType; var valueFactory = new Func <T>(() => (T)context.ResolveComponent(valueRegistration, p)); return(Activator.CreateInstance(lazyType, valueFactory, metadata)); }) .As(providedService) .Targeting(valueRegistration); return(rb.CreateRegistration()); }
protected override void AttachToComponentRegistration( IComponentRegistry registry, IComponentRegistration registration) { registration.Preparing += AddLoggerParameter; }
protected override void AttachToComponentRegistration(IComponentRegistryBuilder componentRegistry, IComponentRegistration registration) { if (_skipRegistration) { return; } // 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(LoggerProvider))) { return; } PropertyInfo[] targetProperties = null; var ra = registration.Activator as ReflectionActivator; if (ra != null) { // 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 (Exception ex) when(ex.GetType().Name == "NoConstructorsFoundException") // Avoid needing to upgrade our Autofac reference to 4.7.0 { ctors = new ConstructorInfo[0]; } var usesLogger = ctors.SelectMany(ctor => ctor.GetParameters()).Any(pi => pi.ParameterType == typeof(ILogger)); if (_autowireProperties) { var logProperties = ra.LimitType .GetRuntimeProperties() .Where(c => c.CanWrite && c.PropertyType == typeof(ILogger) && c.SetMethod.IsPublic && !c.SetMethod.IsStatic) .ToArray(); if (logProperties.Any()) { targetProperties = logProperties; usesLogger = true; } } // Ignore components known to be without logger dependencies if (!usesLogger) { return; } } registration.Preparing += (sender, args) => { var log = args.Context.Resolve <ILogger>().ForContext(registration.Activator.LimitType); args.Parameters = new[] { TypedParameter.From(log) }.Concat(args.Parameters); }; if (targetProperties != null) { registration.Activating += (sender, args) => { var log = args.Context.Resolve <ILogger>().ForContext(registration.Activator.LimitType); foreach (var targetProperty in targetProperties) { targetProperty.SetValue(args.Instance, log); } }; } }
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { base.AttachToComponentRegistration(componentRegistry, registration); Registrations.Add(registration); }
/// <summary> /// Implement the AttachToComponentRegistration, to register logging /// </summary> /// <param name="componentRegistry">IComponentRegistry</param> /// <param name="registration">IComponentRegistration</param> protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { if (!componentRegistry.Properties.ContainsKey(LogActivation) || !string.Equals(bool.TrueString, componentRegistry.Properties[LogActivation] as string, StringComparison.OrdinalIgnoreCase)) { return; } registration.Preparing += RegistrationOnPreparing; registration.Activating += RegistrationOnActivating; registration.Activated += RegistrationOnActivated; }
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { registration.Preparing += OnComponentPreparing; }
/// <summary> /// Resolve an instance of the provided registration within the context. /// </summary> /// <param name="registration">The registration.</param> /// <param name="parameters">Parameters for the instance.</param> /// <returns> /// The component instance. /// </returns> /// <exception cref="ComponentNotRegisteredException"/> /// <exception cref="Autofac.Core.DependencyResolutionException"/> public object ResolveComponent(IComponentRegistration registration, IEnumerable <Parameter> parameters) { return(_containerProvider.RequestLifetime.ResolveComponent(registration, parameters)); }
/// <summary> /// Initializes a new instance of the <see cref="ComponentRegistrationLifetimeDecorator"/> class. /// </summary> /// <param name="inner">The inner registration.</param> /// <param name="lifetime">The enforced lifetime.</param> public ComponentRegistrationLifetimeDecorator(IComponentRegistration inner, IComponentLifetime lifetime) { _inner = inner ?? throw new ArgumentNullException(nameof(inner)); Lifetime = lifetime ?? throw new ArgumentNullException(nameof(lifetime)); }
protected override void AttachToComponentRegistration(IComponentRegistry registry, IComponentRegistration registration) { registration.Activated += OnComponentActivated; }
/// <summary> /// Continue building the object graph by instantiating <paramref name="registration"/> in the /// current <paramref name="currentOperationScope"/>. /// </summary> /// <param name="currentOperationScope">The current scope of the operation.</param> /// <param name="registration">The component to activate.</param> /// <param name="parameters">The parameters for the component.</param> /// <returns>The resolved instance.</returns> /// <exception cref="ArgumentNullException"/> public object GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable <Parameter> parameters) { if (_ended) { throw new ObjectDisposedException(ResolveOperationResources.TemporaryContextDisposed, innerException: null); } ++_callDepth; if (_activationStack.Count > 0) { CircularDependencyDetector.CheckForCircularDependency(registration, _activationStack, _callDepth); } var activation = new InstanceLookup(registration, this, currentOperationScope, parameters); _activationStack.Push(activation); var handler = InstanceLookupBeginning; handler?.Invoke(this, new InstanceLookupBeginningEventArgs(activation)); var instance = activation.Execute(); _successfulActivations.Add(activation); _activationStack.Pop(); if (_activationStack.Count == 0) { CompleteActivations(); } --_callDepth; return(instance); }
public ExternalComponentRegistration(Guid id, IInstanceActivator activator, IComponentLifetime lifetime, InstanceSharing sharing, InstanceOwnership ownership, IEnumerable <Service> services, IDictionary <string, object?> metadata, IComponentRegistration target, bool isAdapterForIndividualComponent) : base(id, activator, lifetime, sharing, ownership, services, metadata, target, isAdapterForIndividualComponent) { }