public IEnumerable <IComponentRegistration> RegistrationsFor(Autofac.Core.Service service, Func <Autofac.Core.Service, IEnumerable <IComponentRegistration> > registrationAccessor) { if (!(service is IServiceWithType swt) || !typeof(SomeEntity).IsAssignableFrom(swt.ServiceType)) { // the requested registration cannot be provided by this source return(Enumerable.Empty <IComponentRegistration>()); } var registration = new ComponentRegistration( Guid.NewGuid(), new DelegateActivator(swt.ServiceType, (c, p) => { var provider = c.Resolve <IConfigurationProvider>(); var config = Activator.CreateInstance(swt.ServiceType); var method = provider.GetType() .GetMethod(nameof(IConfigurationProvider.Get)) ?.MakeGenericMethod(swt.ServiceType); return(method?.Invoke(provider, new[] { config })); }), new CurrentScopeLifetime(), InstanceSharing.None, InstanceOwnership.OwnedByLifetimeScope, new [] { service }, new Dictionary <string, object>()); return(new IComponentRegistration[] { registration }); }
IEnumerable<IComponentRegistration> IRegistrationSource.RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { var typed = service as TypedService; if (lastEvent != null && typed != null) { if (typed.ServiceType.IsAssignableFrom(lastEvent.GetType())) { return new[] { RegistrationBuilder.CreateRegistration(RegistrationBuilder.ForDelegate( typed.ServiceType, (c, p) => lastEvent)) }; } else if (lastEvent.EventArgs != null && typed.ServiceType.IsAssignableFrom(lastEvent.EventArgs.GetType())) { return new[] { RegistrationBuilder.CreateRegistration(RegistrationBuilder.ForDelegate( typed.ServiceType, (c, p) => lastEvent)) }; } } return Enumerable.Empty<IComponentRegistration>(); }
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { if (service == null) throw new ArgumentNullException("service"); if (registrationAccessor == null) throw new ArgumentNullException("registrationAccessor"); Type constructedImplementationType; IEnumerable<Service> services; if (OpenGenericServiceBinder.TryBindServiceType(service, _registrationData.Services, _activatorData.ImplementationType, out constructedImplementationType, out services)) { var swt = (IServiceWithType)service; var fromService = _activatorData.FromService.ChangeType(swt.ServiceType); return registrationAccessor(fromService) .Select(cr => RegistrationBuilder.CreateRegistration( Guid.NewGuid(), _registrationData, new ReflectionActivator( constructedImplementationType, _activatorData.ConstructorFinder, _activatorData.ConstructorSelector, AddDecoratedComponentParameter(swt.ServiceType, cr, _activatorData.ConfiguredParameters), _activatorData.ConfiguredProperties), services)); } return Enumerable.Empty<IComponentRegistration>(); }
/// <summary> /// Create an instance of <see cref="LightweightAdapterActivatorData"/>. /// </summary> /// <param name="fromService">The service that will be adapted from.</param> /// <param name="adapter">The adapter function.</param> public LightweightAdapterActivatorData( Service fromService, Func<IComponentContext, IEnumerable<Parameter>, object, object> adapter) { FromService = fromService; Adapter = adapter; }
/// <summary> /// Retrieve registrations for an unregistered service, to be used /// by the container. /// </summary> /// <param name="service">The service that was requested.</param> /// <param name="registrationAccessor">A function that will return existing registrations for a service.</param> /// <returns>Registrations providing the service.</returns> public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { if (service == null) throw new ArgumentNullException("service"); if (registrationAccessor == null) throw new ArgumentNullException("registrationAccessor"); var ts = service as IServiceWithType; if (ts != null && ts.ServiceType.IsDelegate()) { var resultType = ts.ServiceType.FunctionReturnType(); var resultTypeService = ts.ChangeType(resultType); return registrationAccessor(resultTypeService) .Select(r => { var factory = new FactoryGenerator(ts.ServiceType, r, ParameterMapping.Adaptive); var rb = RegistrationBuilder.ForDelegate(ts.ServiceType, factory.GenerateFactory) .InstancePerLifetimeScope() .ExternallyOwned() .As(service) .Targeting(r); return rb.CreateRegistration(); }); } return Enumerable.Empty<IComponentRegistration>(); }
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { var ts = service as TypedService; if (ts == null || ts.ServiceType.IsAbstract || !ts.ServiceType.IsClass) yield break; IRegistrationBuilder<object, ConcreteReflectionActivatorData, SingleRegistrationStyle> rb = RegistrationBuilder.ForType(ts.ServiceType); yield return rb.CreateRegistration(); }
public IEnumerable <IComponentRegistration> RegistrationsFor(Autofac.Core.Service service, Func <Autofac.Core.Service, IEnumerable <IComponentRegistration> > registrationAccessor) { if (!(service is IServiceWithType) || service is DecoratorService) { return(Enumerable.Empty <IComponentRegistration>()); } if (!service.Description.Contains("Domain0")) { return(Enumerable.Empty <IComponentRegistration>()); } var accessors = registrationAccessor(service); if (accessors.Any()) { return(Enumerable.Empty <IComponentRegistration>()); } var type = service as IServiceWithType; var mock = CreateFake(type.ServiceType); var mockType = mock.GetType(); var serviceRegistration = new ComponentRegistration( Guid.NewGuid(), new DelegateActivator(type.ServiceType, (c, p) => mock), new CurrentScopeLifetime(), InstanceSharing.None, InstanceOwnership.OwnedByLifetimeScope, new[] { service }, new Dictionary <string, object>()); return(new[] { serviceRegistration }); }
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, System.Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { var typedService = service as TypedService; if ( typedService != null ) { if (typedService.ServiceType.IsGenericType) { var genericTypeDefinition = typedService.ServiceType.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(ConfigurationModelHandle<>)) { var modelType = typedService.ServiceType.GetGenericArguments()[0]; if (Attribute.GetCustomAttribute(modelType, typeof(ConfigurationModelAttribute)) != null) { var mappingMethod = tryGetConfigurationModelMethod.MakeGenericMethod(modelType); var mappingParameters = new object[] {configurationProvider, environments, null}; var mappingResult = (bool)mappingMethod.Invoke(null,mappingParameters); if (mappingResult) { var registrationBuilder = RegistrationBuilder.ForDelegate((c, parameters) => mappingParameters[2]).SingleInstance().As(typedService); var registration = registrationBuilder.CreateRegistration(); return new[] { registration }; } } } } } return Enumerable.Empty<IComponentRegistration>(); }
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { if (service == null) throw new ArgumentNullException("service"); var typedService = service as TypedService; if ((typedService == null)) yield break; var newGuid = Guid.NewGuid(); var registration = new ComponentRegistration( newGuid, new DelegateActivator(typedService.ServiceType, (c, p) => { try { return MockRepository.GenerateStub(typedService.ServiceType); } catch (Exception ex) { Type valueType = typedService.ServiceType; throw new ResolutionException(string.Format(CultureInfo.InvariantCulture, "Error while resolving {0}", valueType), ex); } }), new RootScopeLifetime(), InstanceSharing.Shared, InstanceOwnership.OwnedByLifetimeScope, new Service[] { new UniqueService(newGuid), typedService}, new Dictionary<string, object>()); yield return registration; }
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { var serviceWithType = service as IServiceWithType; if (serviceWithType == null) yield break; var serviceType = serviceWithType.ServiceType; if (!serviceType.IsInterface || !typeof(IEventHandler).IsAssignableFrom(serviceType) || serviceType == typeof(IEventHandler)) yield break; var interfaceProxyType = _proxyBuilder.CreateInterfaceProxyTypeWithoutTarget( serviceType, new Type[0], ProxyGenerationOptions.Default); var rb = RegistrationBuilder .ForDelegate((ctx, parameters) => { var interceptors = new IInterceptor[] { new EventsInterceptor(ctx.Resolve<IEventBus>()) }; var args = new object[] { interceptors, null }; return Activator.CreateInstance(interfaceProxyType, args); }) .As(service); yield return rb.CreateRegistration(); }
/// <summary> /// Retrieve registrations for an unregistered service, to be used /// by the container. /// </summary> /// <param name="service">The service that was requested.</param> /// <param name="registrationAccessor">A function that will return existing registrations for a service.</param> /// <returns>Registrations providing the service.</returns> /// <remarks> /// If the source is queried for service s, and it returns a component that implements both s and s', then it /// will not be queried again for either s or s'. This means that if the source can return other implementations /// of s', it should return these, plus the transitive closure of other components implementing their /// additional services, along with the implementation of s. It is not an error to return components /// that do not implement <paramref name="service"/>. /// </remarks> public IEnumerable<IComponentRegistration> RegistrationsFor( Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { if (service == null) throw new ArgumentNullException(nameof(service)); if (registrationAccessor == null) throw new ArgumentNullException(nameof(registrationAccessor)); int contravariantParameterIndex; var swt = service as IServiceWithType; if (swt == null || !IsCompatibleInterfaceType(swt.ServiceType, out contravariantParameterIndex)) return Enumerable.Empty<IComponentRegistration>(); var args = swt.ServiceType.GetTypeInfo().GenericTypeArguments; var definition = swt.ServiceType.GetGenericTypeDefinition(); var contravariantParameter = args[contravariantParameterIndex]; var possibleSubstitutions = GetTypesAssignableFrom(contravariantParameter); var variations = possibleSubstitutions .Select(s => SubstituteArrayElementAt(args, s, contravariantParameterIndex)) .Where(a => definition.IsCompatibleWithGenericParameterConstraints(a)) .Select(a => definition.MakeGenericType(a)); var variantRegistrations = variations .SelectMany(v => registrationAccessor(swt.ChangeType(v))) .Where(r => !r.Metadata.ContainsKey(IsContravariantAdapter)); return variantRegistrations .Select(vr => RegistrationBuilder .ForDelegate((c, p) => c.ResolveComponent(vr, p)) .Targeting(vr) .As(service) .WithMetadata(IsContravariantAdapter, true) .CreateRegistration()); }
public IEnumerable<IComponentRegistration> RegistrationsFor( Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAcessor) { var serviceWithType = service as IServiceWithType; if (serviceWithType == null) { yield break; } // Only introduce services that are not already registered if (registrationAcessor(service).Any()) { yield break; } var serviceType = serviceWithType.ServiceType; if (serviceType == typeof(FallbackScope)) { // This is where we rescope the _fallbackServiceProvider for use in inner scopes // When we actually resolve fallback services, we first access the scoped fallback // service provider by resolving FallbackScope and using its ServiceProvider property. yield return RegistrationBuilder.ForDelegate(serviceType, (context, p) => { var lifetime = context.Resolve<ILifetimeScope>() as ISharingLifetimeScope; if (lifetime != null) { var parentLifetime = lifetime.ParentLifetimeScope; FallbackScope parentFallback; if (parentLifetime != null && parentLifetime.TryResolve<FallbackScope>(out parentFallback)) { var scopeFactory = parentFallback.ServiceProvider .GetServiceOrDefault<IServiceScopeFactory>(); if (scopeFactory != null) { return new FallbackScope(scopeFactory.CreateScope()); } } } return new FallbackScope(_fallbackServiceProvider); }) .InstancePerLifetimeScope() .CreateRegistration(); } else if (_fallbackServiceProvider.GetServiceOrNull(serviceType) != null) { yield return RegistrationBuilder.ForDelegate(serviceType, (context, p) => { var fallbackScope = context.Resolve<FallbackScope>(); return fallbackScope.ServiceProvider.GetService(serviceType); }) .PreserveExistingDefaults() .CreateRegistration(); } }
/// <summary> /// Initializes a new instance of the <see cref="InterceptAttribute"/> class. /// </summary> /// <param name="interceptorService">The interceptor service.</param> /// <exception cref="System.ArgumentNullException">interceptorService</exception> public InterceptAttribute(Service interceptorService) { if (interceptorService == null) throw new ArgumentNullException("interceptorService"); InterceptorService = interceptorService; }
/// <summary> /// Create a new GeneratedFactoryActivatorData /// </summary> /// <param name="delegateType">The type of the factory.</param> /// <param name="productService">The service used to provide the products of the factory.</param> public GeneratedFactoryActivatorData(Type delegateType, Service productService) { if (delegateType == null) throw new ArgumentNullException(nameof(delegateType)); if (productService == null) throw new ArgumentNullException(nameof(productService)); _delegateType = delegateType; _productService = productService; }
public void Constructor_DetectsNullsAmongServices() { Assert.Throws<ArgumentException>(delegate { var services = new Service[] { new TypedService(typeof(object)), null }; Factory.CreateSingletonRegistration(services, Factory.CreateProvidedInstanceActivator(new object())); }); }
/// <summary> /// Initializes a new instance of the <see cref="InterceptAttribute"/> class. /// </summary> /// <param name="interceptorService">The interceptor service.</param> /// <exception cref="System.ArgumentNullException">interceptorService</exception> public InterceptAttribute(Autofac.Core.Service interceptorService) { if (interceptorService == null) { throw new ArgumentNullException("interceptorService"); } InterceptorService = interceptorService; }
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { var s = service as IServiceWithType; if (s != null && s.ServiceType.IsClass && s.ServiceType.Name.EndsWith("Settings")) { yield return RegistrationBuilder.ForDelegate((c, p) => c.Resolve<ISettingsFactory>().Create(s.ServiceType)) .As(s.ServiceType) .SingleInstance() .CreateRegistration(); } }
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { var typedService = service as IServiceWithType; if (typedService != null && IsSupportedView(typedService.ServiceType)) yield return RegistrationBuilder.ForType(typedService.ServiceType) .PropertiesAutowired() .InstancePerDependency() .CreateRegistration(); }
/// <summary> /// Retrieve registrations for an unregistered service, to be used /// by the container. /// </summary> /// <param name="service">The service that was requested.</param> /// <param name="registrationAccessor">A function that will return existing registrations for a service.</param> /// <returns> /// Registrations providing the service. /// </returns> public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { var ts = service as TypedService; if (ts != null && !ts.ServiceType.IsAbstract && ts.ServiceType.IsClass) { var rb = RegistrationBuilder.ForType(ts.ServiceType); return new[] { RegistrationBuilder.CreateRegistration(rb) }; } return Enumerable.Empty<IComponentRegistration>(); }
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { var typedService = service as IServiceWithType; if (typedService != null && typedService.ServiceType.IsClass && typedService.ServiceType.Name.EndsWith("Settings")) { yield return RegistrationBuilder.ForDelegate( (c, p) => c.Resolve<ISettingsReader>().Read(typedService.ServiceType) ).As(typedService.ServiceType) .CreateRegistration(); } }
/// <summary> /// Registrations for /// </summary> /// <param name="service">Service</param> /// <param name="registrations">Registrations</param> /// <returns>Registrations</returns> public IEnumerable <IComponentRegistration> RegistrationsFor( Autofac.Core.Service service, Func <Autofac.Core.Service, IEnumerable <IComponentRegistration> > registrations) { var ts = service as TypedService; if (ts != null && typeof(ISettings).IsAssignableFrom(ts.ServiceType)) { var buildMethod = BuildMethod.MakeGenericMethod(ts.ServiceType); yield return((IComponentRegistration)buildMethod.Invoke(null, null)); } }
private static string GetServiceType(Autofac.Core.Service service) { if (service is TypedService) { return(GetShortTypeName(((TypedService)service).ServiceType)); } if (service is KeyedService) { return(GetShortTypeName(((KeyedService)service).ServiceType)); } return(service.Description); }
private static string GetServiceType(Autofac.Core.Service service) { if (service is TypedService typedService) { return(CsUtility.GetShortTypeName(typedService.ServiceType)); } if (service is KeyedService keyedService) { return(CsUtility.GetShortTypeName(keyedService.ServiceType)); } return(service.Description); }
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { if (service == null) throw new ArgumentNullException(nameof(service)); if (registrationAccessor == null) throw new ArgumentNullException(nameof(registrationAccessor)); if (_registrationData.Services.Contains(service)) { return registrationAccessor(_activatorData.FromService) .Select(r => { var rb = RegistrationBuilder .ForDelegate((c, p) => _activatorData.Adapter(c, p, c.ResolveComponent(r, Enumerable.Empty<Parameter>()))) .Targeting(r); rb.RegistrationData.CopyFrom(_registrationData, true); return rb.CreateRegistration(); }); } var requestedServiceWithType = service as IServiceWithType; var adapteeServiceWithType = _activatorData.FromService as IServiceWithType; if ( // requested and adaptee are services with type (requestedServiceWithType != null && adapteeServiceWithType != null) && // avoiding decorators here (requestedServiceWithType.ServiceType != adapteeServiceWithType.ServiceType) && // if this registration source contains requested service's type (_registrationData.Services.OfType<IServiceWithType>().Any(s => s.ServiceType == requestedServiceWithType.ServiceType))) { // we try to find registrations for the adaptee service but preserve info from the requested service e.g. keys var serviceToFind = requestedServiceWithType.ChangeType(adapteeServiceWithType.ServiceType); return registrationAccessor(serviceToFind) .Select(r => { var rb = RegistrationBuilder .ForDelegate((c, p) => _activatorData.Adapter(c, p, c.ResolveComponent(r, Enumerable.Empty<Parameter>()))) .Targeting(r); rb.RegistrationData.CopyFrom(_registrationData, true); // we explicitly add requested service to the RegistrationData rb.RegistrationData.AddService(service); return rb.CreateRegistration(); }); } return new IComponentRegistration[0]; }
/// <summary> /// Retrieve registrations for an unregistered service, to be used /// by the container. /// </summary> /// <param name="service">The service that was requested.</param> /// <param name="registrationAccessor">A function that will return existing registrations for a service.</param> /// <returns>Registrations providing the service.</returns> public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { if (service == null) throw new ArgumentNullException(nameof(service)); if (registrationAccessor == null) throw new ArgumentNullException(nameof(registrationAccessor)); var swt = service as IServiceWithType; if (swt != null) { var serviceType = swt.ServiceType; Type elementType = null; if (serviceType.IsGenericEnumerableInterfaceType()) { elementType = serviceType.GetTypeInfo().GenericTypeArguments.First(); } else if (serviceType.IsArray) { elementType = serviceType.GetElementType(); } if (elementType != null) { var elementTypeService = swt.ChangeType(elementType); var elementArrayType = elementType.MakeArrayType(); var listType = typeof(List<>).MakeGenericType(elementType); var serviceTypeIsList = serviceType.IsGenericListOrCollectionInterfaceType(); var registration = new ComponentRegistration( Guid.NewGuid(), new DelegateActivator(elementArrayType, (c, p) => { var elements = c.ComponentRegistry.RegistrationsFor(elementTypeService); var items = elements.Select(cr => c.ResolveComponent(cr, p)).ToArray(); var result = Array.CreateInstance(elementType, items.Length); items.CopyTo(result, 0); return serviceTypeIsList ? Activator.CreateInstance(listType, result) : result; }), new CurrentScopeLifetime(), InstanceSharing.None, InstanceOwnership.ExternallyOwned, new[] { service }, new Dictionary<string, object>()); return new IComponentRegistration[] { registration }; } } return Enumerable.Empty<IComponentRegistration>(); }
public IEnumerable <IComponentRegistration> RegistrationsFor(Autofac.Core.Service service, Func <Autofac.Core.Service, IEnumerable <IComponentRegistration> > registrationAccessor) { if (service is IServiceWithType ts && (ts.ServiceType.IsInterface || ts.ServiceType.IsAbstract)) { var builder = RegistrationBuilder.ForDelegate((c, p) => Substitute.For(new[] { ts.ServiceType }, null)) .As(service) .InstancePerLifetimeScope(); return(new[] { builder.CreateRegistration() }); } return(Enumerable.Empty <IComponentRegistration>()); }
/// <summary> /// Retrieve registrations for an unregistered service, to be used /// by the container. /// </summary> /// <param name="service">The service that was requested.</param> /// <param name="registrationAccessor">A function that will return existing registrations for a service.</param> /// <returns>Registrations providing the service.</returns> public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { if (service == null) throw new ArgumentNullException("service"); if (registrationAccessor == null) throw new ArgumentNullException("registrationAccessor"); var swt = service as IServiceWithType; if (swt != null) { var serviceType = swt.ServiceType; Type elementType = null; if (serviceType.IsGenericTypeDefinedBy(typeof(IEnumerable<>))) { elementType = serviceType.GetGenericArguments()[0]; } else if (serviceType.IsArray) { elementType = serviceType.GetElementType(); } if (elementType != null) { var elementTypeService = swt.ChangeType(elementType); var elementArrayType = elementType.MakeArrayType(); #if WINDOWS_PHONE //.MakeArrayType() doesn't work for some types on WP7 if (elementArrayType == null) elementArrayType = typeof (IEnumerable<>).MakeGenericType(elementType); #endif var registration = new ComponentRegistration( Guid.NewGuid(), new DelegateActivator(elementArrayType, (c, p) => { var elements = c.ComponentRegistry.RegistrationsFor(elementTypeService); var items = elements.Select(cr => c.ResolveComponent(cr, p)).ToArray(); var result = Array.CreateInstance(elementType, items.Length); items.CopyTo(result, 0); return result; }), new CurrentScopeLifetime(), InstanceSharing.None, InstanceOwnership.ExternallyOwned, new[] { service }, new Dictionary<string, object>()); return new IComponentRegistration[] { registration }; } } return Enumerable.Empty<IComponentRegistration>(); }
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { var serviceWithType = service as IServiceWithType; if (serviceWithType == null) yield break; var serviceType = serviceWithType.ServiceType; if (!typeof(IHub).IsAssignableFrom(serviceType)) yield break; var rb = RegistrationBuilder .ForType(serviceType) .As(typeof (IHub), serviceType) .InstancePerDependency(); yield return rb.CreateRegistration(); }
public IEnumerable <IComponentRegistration> RegistrationsFor(Autofac.Core.Service service, Func <Autofac.Core.Service, IEnumerable <IComponentRegistration> > registrationAccessor) { var components = _source.RegistrationsFor(service, registrationAccessor); foreach (var c in components) { var defs = c.Target.Services .OfType <TypedService>() .Select(x => x.ServiceType.GetGenericTypeDefinition()); if (defs.Any(_types.Contains)) { yield return(c); } } }
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { var typedService = service as IServiceWithType; if (typedService != null && typedService.ServiceType.IsClass && typedService.ServiceType.Name.EndsWith("Settings")) { yield return RegistrationBuilder.ForDelegate( (c, p) => { var instance = Activator.CreateInstance(typedService.ServiceType); c.Resolve<ISettingsInjector>().Inject(instance, c.Resolve<IEnumerable<ISettingsReader>>()); return instance; } ).As(typedService.ServiceType) .CreateRegistration(); } }
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { if (service == null) throw new ArgumentNullException(nameof(service)); var typedService = service as TypedService; if (typedService == null || !typeof(UiComponent).IsAssignableFrom(typedService.ServiceType)) return Enumerable.Empty<IComponentRegistration>(); var rb = RegistrationBuilder.ForType(typedService.ServiceType) .As(service) .InstancePerDependency() .OnActivatedInitialiseUiComponent(); return new[] { rb.CreateRegistration() }; }
/// <summary> /// Retrieve registrations for an unregistered service, to be used by the container. /// </summary> /// <param name="service">The service that was requested.</param> /// <param name="registrationAccessor">A function that will return existing registrations for a service.</param> /// <returns>Registrations providing the service.</returns> public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { var typedService = service as TypedService; if (typedService != null) { var instances = base.GetServices(typedService.ServiceType); if (instances != null) { return instances .Select(i => RegistrationBuilder.ForDelegate(i.GetType(), (c, p) => i).As(typedService.ServiceType) .InstancePerMatchingLifetimeScope(_lifetimeScope.Tag) .PreserveExistingDefaults() .CreateRegistration()); } } return Enumerable.Empty<IComponentRegistration>(); }
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { var swt = service as IServiceWithType; if (swt == null) { yield break; } if (_onlyInterfaces && !swt.ServiceType.IsInterface) { yield break; } var existingReg = registrationAccessor(service); if (existingReg.Any()) { yield break; } var reg = RegistrationBuilder.ForDelegate((c, p) => { var constructors = swt.ServiceType.GetConstructors(); if (constructors.Any() && !constructors.Any(ctor => !ctor.GetParameters().Any())) { var constructor = constructors.First(); List<object> parameterValues = new List<object>(); foreach (var parameterInfo in constructor.GetParameters()) { parameterValues.Add(c.Resolve(parameterInfo.ParameterType)); } var createMethodWithArgs = _createWithArgsMethod.MakeGenericMethod(swt.ServiceType); var mockWithArgs = ((Mock)createMethodWithArgs.Invoke(_repository, new object[] { parameterValues.ToArray() })); return mockWithArgs.Object; } var createMethod = _createMethod.MakeGenericMethod(swt.ServiceType); var mock = ((Mock)createMethod.Invoke(_repository, null)); return mock.Object; }).As(swt.ServiceType).SingleInstance().CreateRegistration(); yield return reg; }
public static bool TryBindServiceType( Service service, IEnumerable<Service> configuredOpenGenericServices, Type openGenericImplementationType, out Type constructedImplementationType, out IEnumerable<Service> constructedServices) { var swt = service as IServiceWithType; if (swt != null && swt.ServiceType.IsGenericType) { var definitionService = (IServiceWithType)swt.ChangeType(swt.ServiceType.GetGenericTypeDefinition()); var serviceGenericArguments = swt.ServiceType.GetGenericArguments(); if (configuredOpenGenericServices.Cast<IServiceWithType>().Any(s => s.Equals(definitionService))) { var implementorGenericArguments = TryMapImplementationGenericArguments( openGenericImplementationType, swt.ServiceType, definitionService.ServiceType, serviceGenericArguments); if (!implementorGenericArguments.Any(a => a == null) && openGenericImplementationType.IsCompatibleWithGenericParameterConstraints(implementorGenericArguments)) { var constructedImplementationTypeTmp = openGenericImplementationType.MakeGenericType(implementorGenericArguments); // This needs looking at var implementedServices = (from IServiceWithType s in configuredOpenGenericServices let genericService = s.ServiceType.MakeGenericType(serviceGenericArguments) where genericService.IsAssignableFrom(constructedImplementationTypeTmp) select s.ChangeType(genericService)).ToArray(); if (implementedServices.Length > 0) { constructedImplementationType = constructedImplementationTypeTmp; constructedServices = implementedServices; return true; } } } } constructedImplementationType = null; constructedServices = null; return false; }
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { // Here is where you define your "global interceptor list" var interceptorServices = new Service[] { new TypedService(typeof(CacheInterceptor)) }; // Append the global interceptors to any existing list, or create a new interceptor // list if none are specified. Note this info will only be used by registrations // that are set to have interceptors enabled. It'll be ignored by others. object existing; if (registration.Metadata.TryGetValue(InterceptorsPropertyName, out existing)) { registration.Metadata[InterceptorsPropertyName] = ((IEnumerable<Service>)existing).Concat(interceptorServices).Distinct(); } else { registration.Metadata.Add(InterceptorsPropertyName, interceptorServices); } }
/// <summary> /// Retrieve registrations for an unregistered service, to be used /// by the container. /// </summary> /// <param name="service">The service that was requested.</param> /// <param name="registrationAccessor">A function that will return existing registrations for a service.</param> /// <returns>Registrations providing the service.</returns> public IEnumerable<IComponentRegistration> RegistrationsFor( Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { if (registrationAccessor == null) throw new ArgumentNullException(nameof(registrationAccessor)); var ts = service as TypedService; if (ts == null || !ts.ServiceType.GetTypeInfo().IsClass || ts.ServiceType.GetTypeInfo().IsSubclassOf(typeof(Delegate)) || ts.ServiceType.GetTypeInfo().IsAbstract || !_predicate(ts.ServiceType) || registrationAccessor(service).Any()) return Enumerable.Empty<IComponentRegistration>(); var builder = RegistrationBuilder.ForType(ts.ServiceType); RegistrationConfiguration?.Invoke(builder); return new[] {builder.CreateRegistration()}; }
/// <summary> /// Retrieve a registration for an unregistered service, to be used /// by the container. /// </summary> /// <param name="service">The service that was requested.</param> /// <param name="registrationAccessor"></param> /// <returns> /// Registrations for the service. /// </returns> public IEnumerable<IComponentRegistration> RegistrationsFor (Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { if (service == null) throw new ArgumentNullException("service"); var typedService = service as TypedService; if (typedService == null || !typedService.ServiceType.IsInterface || typedService.ServiceType.IsGenericType && typedService.ServiceType.GetGenericTypeDefinition() == typeof(IEnumerable<>) || typedService.ServiceType.IsArray || typeof(IStartable).IsAssignableFrom(typedService.ServiceType)) return Enumerable.Empty<IComponentRegistration>(); var rb = RegistrationBuilder.ForDelegate((c, p) => Substitute.For(new[] { typedService.ServiceType }, null)) .As(service) .InstancePerLifetimeScope(); return new[] { rb.CreateRegistration() }; }
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { var result = inner.RegistrationsFor(service, registrationAccessor); foreach (var registration in result) { registration.Activating += (sender, args) => { if (args.Instance.GetType().IsSubclassOf(typeof (Scenario))) { var scenario = (Scenario)args.Instance; scenario.Client = args.Context.Resolve<IClient>(); scenario.Server = args.Context.Resolve<IServer>(); scenario.Soap = args.Context.Resolve<ISoapDecoder>(); scenario.Data = args.Context.Resolve<ITestDataLoader>(); scenario.Container = args.Context.Resolve<ILifetimeScope>(); } }; yield return registration; } }
public IEnumerable <IComponentRegistration> RegistrationsFor( Autofac.Core.Service service, Func <Autofac.Core.Service, IEnumerable <IComponentRegistration> > registrationAccessor) { if (!(service is IServiceWithType swt)) { return(Enumerable.Empty <IComponentRegistration>()); } // TODO: Need to investigate this, is not the proper solution if (service is DecoratorService) { return(Enumerable.Empty <IComponentRegistration>()); } Type serviceType = swt.ServiceType; // Ensure is IEnumerable<IPipelineBehavior<,>> if (IsGenericTypeDefined(serviceType, typeof(IEnumerable <>))) { Type enumerableItemType = serviceType.GetGenericArguments().First(); if (IsGenericTypeDefined(enumerableItemType, typeof(IPipelineBehavior <,>))) { Type[] genericTypes = enumerableItemType.GetGenericArguments(); Type requestType = genericTypes[0]; // IQuery<> or ICommand<> Type responseType = genericTypes[1]; // IResponse<TResult> Type resultType = responseType.GetGenericArguments().Single(); // TResult Autofac.Core.Service closePipeline = swt.ChangeType(typeof(IPipelineBehaviour <, ,>).MakeGenericType(new[] { requestType, responseType, resultType })); var activator = new DelegateActivator( enumerableItemType.MakeArrayType(), (ctx, parameters) => { IEnumerable <IComponentRegistration> registrations = ctx.ComponentRegistry.RegistrationsFor(closePipeline); IEnumerable <object> instances = registrations .Select(componentRegistration => ctx.ResolveComponent(componentRegistration, parameters)) .Reverse() .ToArray(); return(OfType(instances, enumerableItemType)); } ); IComponentRegistration registration = new ComponentRegistration( Guid.NewGuid(), activator, new CurrentScopeLifetime(), InstanceSharing.None, InstanceOwnership.OwnedByLifetimeScope, new[] { service }, new Dictionary <string, object>() ); return(new IComponentRegistration[] { registration }); } } return(Enumerable.Empty <IComponentRegistration>()); }