/// <summary> /// Creates a mock object. /// </summary> /// <param name="context">The component context.</param> /// <param name="typedService">The typed service.</param> /// <returns> /// The mock object from the repository. /// </returns> private object CreateMock(IComponentContext context, IServiceWithType typedService) { var specificCreateMethod = this._createMethod.MakeGenericMethod(new[] { typedService.ServiceType }); var mock = (Mock)specificCreateMethod.Invoke(context.Resolve <MockRepository>(), null); return(mock.Object); }
public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor) { IServiceWithType typedService = service as IServiceWithType; if (typedService == null) { return(Enumerable.Empty <IComponentRegistration>()); } if (!(typedService.ServiceType.IsGenericType && typedService.ServiceType.GetGenericTypeDefinition() == typeof(IEnumerable <>))) { return(Enumerable.Empty <IComponentRegistration>()); } Type elementType = typedService.ServiceType.GetGenericArguments()[0]; Service elementService = typedService.ChangeType(elementType); Type collectionType = typeof(List <>).MakeGenericType(elementType); IComponentRegistration registration = RegistrationBuilder.ForDelegate(collectionType, (c, p) => { IEnumerable <IComponentRegistration> registrations = c.ComponentRegistry.RegistrationsFor(elementService); IEnumerable <Object> elements = registrations.Select(cr => c.ResolveComponent(cr, p)); // get distinct elements by type Array array = elements.GroupBy(o => o.GetType()).Select(o => o.First()).ToArray(); Array array2 = Array.CreateInstance(elementType, array.Length); array.CopyTo(array2, 0); Object collection = Activator.CreateInstance(collectionType, new Object[] { array2 }); return(collection); }).As(service) .CreateRegistration(); return(new IComponentRegistration[] { registration }); }
private static IEnumerable<IComponentRegistration> AdaptFactories(Type from, Type to, IServiceWithType requestedService, Func<AutofacService, IEnumerable<IComponentRegistration>> registrationAccessor) { Guard.NotNull("from", from); Guard.NotNull("to", to); Guard.NotNull("requestedService", requestedService); Guard.NotNull("registrationAccessor", registrationAccessor); var factoryService = new OpenGenericLooselyNamedService(String.Empty, from); return registrationAccessor(factoryService) .Select(r => { var targetService = r.Services.OfType<OpenGenericLooselyNamedService>().First(s => factoryService.Equals(s)); return new ComponentRegistration( Guid.NewGuid(), new DelegateActivator( requestedService.ServiceType, (c, p) => Activator.CreateInstance( // Since we looked up factory interfaces only (from argument) - generic argument of s.ServiceType will be the type of configuration to.MakeGenericType(targetService.ServiceType.GetGenericArguments()[0]), c.ResolveComponent(r, Enumerable.Empty<Parameter>()), GetDisplayName(r.Metadata, targetService.Name)) ), new CurrentScopeLifetime(), InstanceSharing.None, InstanceOwnership.ExternallyOwned, new AutofacService[] { new LooselyNamedService(targetService.Name, requestedService.ServiceType) }, new Dictionary<string, object>()); }); }
/// <summary> /// Given a closed generic service (that is being requested), creates a regular delegate callback /// and associated services from the open generic delegate and services. /// </summary> /// <param name="serviceWithType">The closed generic service to bind.</param> /// <param name="configuredOpenGenericServices">The set of configured open generic services.</param> /// <param name="openGenericFactory">Delegate responsible for generating an instance of a closed generic based on the open generic type being registered.</param> /// <param name="constructedFactory">The built closed generic implementation type.</param> /// <param name="constructedServices">The built closed generic services.</param> /// <returns>True if the closed generic service can be bound. False otherwise.</returns> public static bool TryBindOpenGenericDelegateService( IServiceWithType serviceWithType, IEnumerable <Service> configuredOpenGenericServices, Func <IComponentContext, Type[], IEnumerable <Parameter>, object> openGenericFactory, [NotNullWhen(returnValue: true)] out Func <IComponentContext, IEnumerable <Parameter>, object>?constructedFactory, [NotNullWhen(returnValue: true)] out Service[]?constructedServices) { if (serviceWithType.ServiceType.IsGenericType && !serviceWithType.ServiceType.IsGenericTypeDefinition) { var definitionService = (IServiceWithType)serviceWithType.ChangeType(serviceWithType.ServiceType.GetGenericTypeDefinition()); var serviceGenericArguments = serviceWithType.ServiceType.GetGenericArguments(); if (configuredOpenGenericServices.Cast <IServiceWithType>().Any(s => s.Equals(definitionService))) { constructedFactory = (ctx, parameters) => openGenericFactory(ctx, serviceGenericArguments, parameters); var implementedServices = configuredOpenGenericServices .OfType <IServiceWithType>() .Where(s => s.ServiceType.GetGenericArguments().Length == serviceGenericArguments.Length) .Select(s => new { ServiceWithType = s, GenericService = s.ServiceType.MakeGenericType(serviceGenericArguments) }) .Select(p => p.ServiceWithType.ChangeType(p.GenericService)) .ToArray(); constructedServices = implementedServices; return(true); } } constructedFactory = null; constructedServices = null; return(false); }
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"); } IServiceWithType ts = service as IServiceWithType; if ((ts == null) || !ts.ServiceType.IsGenericTypeDefinedBy(typeof(Owned <>))) { return(Enumerable.Empty <IComponentRegistration>()); } Type newType = ts.ServiceType.GetGenericArguments()[0]; Service ownedInstanceService = ts.ChangeType(newType); return(from r in registrationAccessor(ownedInstanceService) select RegistrationBuilder.ForDelegate(ts.ServiceType, delegate(IComponentContext c, IEnumerable <Parameter> p) { object obj3; ILifetimeScope scope = c.Resolve <ILifetimeScope>().BeginLifetimeScope(ownedInstanceService); try { object obj2 = scope.ResolveComponent(r, p); obj3 = Activator.CreateInstance(ts.ServiceType, new object[] { obj2, scope }); } catch { scope.Dispose(); throw; } return obj3; }).ExternallyOwned().As(new Service[] { service }).Targeting <object, SimpleActivatorData, SingleRegistrationStyle>(r).CreateRegistration <object, SimpleActivatorData, SingleRegistrationStyle>()); }
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"); } // service must be typed IServiceWithType ts = service as IServiceWithType; // if service not typed or not(ts is generic and generic type definition is of type IEntityRepository if (ts == null || !(ts.ServiceType.IsGenericType && ts.ServiceType.GetGenericTypeDefinition() == typeof(IEntityRepository <>))) //if (ts == null || !(ts.ServiceType.IsGenericType && ts.ServiceType.GetGenericTypeDefinition() == typeof(IEntityRepository))) { yield break; } yield return(RegistrationBuilder.ForType(ts.ServiceType) .AsSelf() .WithParameter(new NamedParameter("databaseName", "test")) .WithParameter(new NamedParameter("serverName", "test2")) .CreateRegistration()); }
private static IEnumerable <IComponentRegistration> AdaptFactories(Type from, Type to, IServiceWithType requestedService, Func <AutofacService, IEnumerable <IComponentRegistration> > registrationAccessor) { Guard.NotNull("from", from); Guard.NotNull("to", to); Guard.NotNull("requestedService", requestedService); Guard.NotNull("registrationAccessor", registrationAccessor); var factoryService = new OpenGenericLooselyNamedService(String.Empty, from); return(registrationAccessor(factoryService) .Select(r => { var targetService = r.Services.OfType <OpenGenericLooselyNamedService>().First(s => factoryService.Equals(s)); return new ComponentRegistration( Guid.NewGuid(), new DelegateActivator( requestedService.ServiceType, (c, p) => Activator.CreateInstance( // Since we looked up factory interfaces only (from argument) - generic argument of s.ServiceType will be the type of configuration to.MakeGenericType(targetService.ServiceType.GetGenericArguments()[0]), c.ResolveComponent(r, Enumerable.Empty <Parameter>()), GetDisplayName(r.Metadata, targetService.Name)) ), new CurrentScopeLifetime(), InstanceSharing.None, InstanceOwnership.ExternallyOwned, new AutofacService[] { new LooselyNamedService(targetService.Name, requestedService.ServiceType) }, new Dictionary <string, object>()); })); }
public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor) { Func <IComponentRegistration, IComponentRegistration> selector = null; if (service == null) { throw new ArgumentNullException("service"); } if (registrationAccessor == null) { throw new ArgumentNullException("registrationAccessor"); } IServiceWithType ts = service as IServiceWithType; if ((ts == null) || !ts.ServiceType.IsDelegate()) { return(Enumerable.Empty <IComponentRegistration>()); } Type newType = ts.ServiceType.FunctionReturnType(); Service arg = ts.ChangeType(newType); if (selector == null) { selector = r => RegistrationBuilder.ForDelegate(ts.ServiceType, new Func <IComponentContext, IEnumerable <Parameter>, object>(new FactoryGenerator(ts.ServiceType, r, ParameterMapping.Adaptive).GenerateFactory)).InstancePerLifetimeScope().ExternallyOwned().As(new Service[] { service }).Targeting <object, SimpleActivatorData, SingleRegistrationStyle>(r).CreateRegistration <object, SimpleActivatorData, SingleRegistrationStyle>(); } return(registrationAccessor(arg).Select <IComponentRegistration, IComponentRegistration>(selector)); }
private static bool IsIEnumerable(IServiceWithType typedService) { // We handle most generics, but we don't handle IEnumerable because that has special // meaning in Autofac return(typedService.ServiceType.GetTypeInfo().IsGenericType&& typedService.ServiceType.GetTypeInfo().GetGenericTypeDefinition() == typeof(IEnumerable <>)); }
private bool CanMockService(IServiceWithType typedService) { return(!_createdServiceTypes.Contains(typedService.ServiceType) && ServiceIsAbstractOrNonSealedOrInterface(typedService) && !IsIEnumerable(typedService) && !IsIStartable(typedService)); }
public ComponentRegistration RegistrationFor(Service service) { var swt = service as IServiceWithType; if (swt == null) { return(null); } Type resolutionType = swt.ServiceType; if (!resolutionType.IsGenericType || !resolutionType.IsConstructedGenericType) { return(null); } IServiceWithType openGenericService = swt.ChangeType(resolutionType.GetGenericTypeDefinition()); if (!openGenericService.Equals(genericService)) { return(null); } Type constructedImplementorType = implementorType.MakeGenericType(resolutionType.GenericTypeArguments); return(new ComponentRegistration( service, new ReflectiveActivator(constructedImplementorType))); }
public void TestAutofacRegistrations() { IContainer container = ServicesContainer.Container; IEnumerable <IServiceWithType> autofacServices = container.ComponentRegistry.Registrations.SelectMany(x => x.Services).OfType <IServiceWithType>(); foreach (IServiceWithType svc in autofacServices) { Console.WriteLine("Resolving registration: '{0}'", svc); IServiceWithType serviceWithType = svc; Assert.DoesNotThrow(() => { KeyedService keyedService = serviceWithType as KeyedService; var resolvedService = keyedService != null ? container.ResolveKeyed(keyedService.ServiceKey, serviceWithType.ServiceType) : container.Resolve(serviceWithType.ServiceType); if (resolvedService == null) { throw new Exception("Autofac service not found: " + serviceWithType.ServiceType.Name); } }, $"Failed to resolve autofac service '{serviceWithType}' or one of it's dependencies" ); } }
/// <summary> /// Gets the display name for a service that should be used in a graph. /// </summary> /// <param name="service">The service for which a display name should be retrieved.</param> /// <returns>A <see cref="string"/> with a human-readable, pretty-printed display name for use in a graph node or label.</returns> public static string GraphDisplayName(this Service service) { return(service switch { IServiceWithType swt => swt.ServiceType.CSharpName(), _ => service.Description });
public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor) { IServiceWithType serviceWithType = service as IServiceWithType; if (serviceWithType == null || !serviceWithType.ServiceType.IsGenericType) { yield break; } if (serviceWithType.ServiceType.GetGenericTypeDefinition() != typeof(Func <>)) { yield break; } Type elementType = serviceWithType.ServiceType.GetGenericArguments()[0]; Type fixedFactoryType = typeof(FixedFactory <>).MakeGenericType(elementType); Service fixedFactoryService = serviceWithType.ChangeType(fixedFactoryType); MethodInfo getInstanceMethod = typeof(FixedFactory <>).MakeGenericType(elementType).GetMethod("GetInstance"); foreach (IComponentRegistration registration in registrationAccessor(fixedFactoryService)) { yield return(RegistrationBuilder.ForDelegate(typeof(Func <>).MakeGenericType(elementType), (c, p) => { // /!\ disposal of this object is not managed Object fixedFactory = c.ResolveComponent(registration, p); return getInstanceMethod.CreateDelegate(typeof(Func <>) .MakeGenericType(elementType), fixedFactory); }) .As(service) .Targeting(registration) .CreateRegistration()); } }
private static Type GetLazyType(IServiceWithType serviceWithType) { return(serviceWithType != null && serviceWithType.ServiceType.GetTypeInfo().IsGenericType && serviceWithType.ServiceType.GetGenericTypeDefinition().FullName == "System.Lazy`2" ? serviceWithType.ServiceType.GetGenericTypeDefinition() : null); }
private static bool ServiceIsAbstractOrNonSealedOrInterface(IServiceWithType typedService) { var serverTypeInfo = typedService.ServiceType.GetTypeInfo(); return(serverTypeInfo.IsInterface || serverTypeInfo.IsAbstract || (serverTypeInfo.IsClass && !serverTypeInfo.IsSealed)); }
private static bool IsMeta(IServiceWithType typedService) { // We handle most generics, but we don't handle Meta because that has special // meaning in Autofac var typeInfo = typedService.ServiceType.GetTypeInfo(); return(typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(Meta <>)); }
static void AssertInstancePerOwnedResolvesToOwnedScope(Owned<MessageHandler> owned, IServiceWithType tag) { var handler = owned.Value; var dependentService = handler.DependentService; Assert.Equal(tag, handler.LifetimeScope.Tag); Assert.Same(handler.LifetimeScope, dependentService.LifetimeScope); }
/// <summary> /// Construct an <see cref="OpenGenericDecoratorActivatorData"/>. /// </summary> /// <param name="implementor">The decorator type.</param> /// <param name="fromService">The open generic service type to decorate.</param> public OpenGenericDecoratorActivatorData(Type implementor, IServiceWithType fromService) : base(implementor) { if (fromService == null) throw new ArgumentNullException("fromService"); if (!fromService.ServiceType.IsGenericTypeDefinition) throw new ArgumentException(string.Format("The service '{0}' is not an open generic type.", fromService)); _fromService = fromService; }
/// <summary> /// Construct an <see cref="OpenGenericDecoratorActivatorData"/>. /// </summary> /// <param name="implementor">The decorator type.</param> /// <param name="fromService">The open generic service type to decorate.</param> public OpenGenericDecoratorActivatorData(Type implementor, IServiceWithType fromService) : base(implementor) { if (fromService == null) throw new ArgumentNullException("fromService"); if (!fromService.ServiceType.IsGenericTypeDefinition) throw new ArgumentException(string.Format(OpenGenericDecoratorActivatorDataResources.DecoratedServiceIsNotOpenGeneric, fromService)); _fromService = fromService; }
private bool ShouldMockService(IServiceWithType typedService) { return(!IsIEnumerable(typedService) && !IsIStartable(typedService) && !IsInsideAutofac(typedService) && !IsLazy(typedService) && !IsOwned(typedService) && !IsMeta(typedService)); }
/// <summary> /// Construct an <see cref="OpenGenericDecoratorActivatorData"/>. /// </summary> /// <param name="implementer">The decorator type.</param> /// <param name="fromService">The open generic service type to decorate.</param> public OpenGenericDecoratorActivatorData(Type implementer, IServiceWithType fromService) : base(implementer) { if (fromService == null) throw new ArgumentNullException(nameof(fromService)); if (!fromService.ServiceType.GetTypeInfo().IsGenericTypeDefinition) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, OpenGenericDecoratorActivatorDataResources.DecoratedServiceIsNotOpenGeneric, fromService)); FromService = fromService; }
public DecoratorComponentRegistry(IComponentRegistry inner, IServiceWithType service) { _inner = inner; _service = service; if (!inner.Properties.TryGetValue(KeysHolder, out var val) || !(val is Dictionary <IServiceWithType, object> keyBucket)) { _keyBucket = new Dictionary <IServiceWithType, object>(); inner.Properties[KeysHolder] = _keyBucket; }
public IComponentRegistration CreateFilteredRegistration <T>(IServiceWithType serviceWithType) { return(RegistrationBuilder.ForDelegate((cc, p) => cc.ComponentRegistry .RegistrationsFor(serviceWithType.ChangeType(typeof(T))) .Where(r => !r.Activator.LimitType.GetCustomAttributes(typeof(ContractClassForAttribute), false).Any()) .Select(r => r.Activator.ActivateInstance(cc, p)) .Cast <T>()) .As((Service)serviceWithType) .CreateRegistration()); }
private static bool ServiceCompatibleWithAutomaticDirectRegistration(IServiceWithType typedService) { var serviceType = typedService.ServiceType; return(serviceType.IsClass && serviceType != typeof(string) && !serviceType.IsSubclassOf(typeof(Delegate)) && !serviceType.IsAbstract && !serviceType.IsGenericTypeDefinition); }
public OpenGenericRegistrationSource( IServiceWithType genericService, Type implementorType, IComponentLifetime lifetime, InstanceSharing sharing) { this.genericService = genericService; this.implementorType = implementorType; this.lifetime = lifetime; this.sharing = sharing; }
private static bool ServiceCompatibleWithMockRepositoryCreate(IServiceWithType typedService) { var serverTypeInfo = typedService.ServiceType.GetTypeInfo(); // Issue #15: Ensure there's a zero-parameter ctor or the DynamicProxy under Moq fails. return(serverTypeInfo.IsInterface || serverTypeInfo.IsAbstract || (serverTypeInfo.IsClass && !serverTypeInfo.IsSealed && typedService.ServiceType.GetConstructors().Any(c => c.GetParameters().Length == 0))); }
public OpenGenericDecoratorActivatorData(Type implementor, IServiceWithType fromService) : base(implementor) { if (fromService == null) { throw new ArgumentNullException("fromService"); } if (!fromService.ServiceType.IsGenericTypeDefinition) { throw new ArgumentException(string.Format(OpenGenericDecoratorActivatorDataResources.DecoratedServiceIsNotOpenGeneric, fromService)); } this._fromService = fromService; }
static Type GetLazyType(IServiceWithType serviceWithType) { return(serviceWithType != null #if !ASPNETCORE50 && serviceWithType.ServiceType.IsGenericType #else && serviceWithType.ServiceType.GetTypeInfo().IsGenericType #endif && serviceWithType.ServiceType.GetGenericTypeDefinition().FullName == "System.Lazy`2" ? serviceWithType.ServiceType.GetGenericTypeDefinition() : null); }
private bool CanMockService(IServiceWithType typedService) { // Since we're calling MockRepository.Create<T>() to auto-mock and we don't provide // parameter support, it means we're limited to only auto-mocking things that can pass // through Moq / Castle.DynamicProxy without any parameters. return(!this._createdServiceTypes.Contains(typedService.ServiceType) && ServiceCompatibleWithMockRepositoryCreate(typedService) && !IsIEnumerable(typedService) && !IsIStartable(typedService) && !IsLazy(typedService) && !IsOwned(typedService) && !IsMeta(typedService)); }
/// <inheritdoc /> public IReadOnlyList <IComponentRegistration> DecoratorsFor(IServiceWithType service) { if (service == null) { throw new ArgumentNullException(nameof(service)); } return(_decorators.GetOrAdd(service, s => RegistrationsFor(new DecoratorService(s.ServiceType)) .Where(r => !r.IsAdapterForIndividualComponent) .OrderBy(r => r.GetRegistrationOrder()) .ToArray())); }
/// <summary> /// Initializes a new instance of the <see cref="OpenGenericDecoratorActivatorData"/> class. /// </summary> /// <param name="implementer">The decorator type.</param> /// <param name="fromService">The open generic service type to decorate.</param> public OpenGenericDecoratorActivatorData(Type implementer, IServiceWithType fromService) : base(implementer) { if (fromService == null) { throw new ArgumentNullException(nameof(fromService)); } if (!fromService.ServiceType.GetTypeInfo().IsGenericTypeDefinition) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, OpenGenericDecoratorActivatorDataResources.DecoratedServiceIsNotOpenGeneric, fromService)); } FromService = fromService; }
/// <summary> /// Construct an <see cref="OpenGenericDecoratorActivatorData"/>. /// </summary> /// <param name="implementor">The decorator type.</param> /// <param name="fromService">The open generic service type to decorate.</param> public OpenGenericDecoratorActivatorData(Type implementor, IServiceWithType fromService) : base(implementor) { if (fromService == null) { throw new ArgumentNullException("fromService"); } if (!fromService.ServiceType.IsGenericTypeDefinition) { throw new ArgumentException(string.Format("The service '{0}' is not an open generic type.", fromService)); } _fromService = fromService; }
public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor) { IServiceWithType type = service as IServiceWithType; if ((type == null) || !type.ServiceType.IsGenericTypeDefinedBy(typeof(Meta <>))) { return(Enumerable.Empty <IComponentRegistration>()); } Type newType = type.ServiceType.GetGenericArguments()[0]; Service arg = type.ChangeType(newType); MethodInfo registrationCreator = CreateMetaRegistrationMethod.MakeGenericMethod(new Type[] { newType }); return((from v in registrationAccessor(arg) select registrationCreator.Invoke(null, new object[] { service, v })).Cast <IComponentRegistration>()); }
private static TypedService GetService(IServiceWithType service) { if (service is AutofacKeyedService) { return(new KeyedService { Key = ((AutofacKeyedService)service).ServiceKey, Type = ((AutofacKeyedService)service).ServiceType }); } return(new TypedService { Type = service.ServiceType }); }
private static TypedService GetService(IServiceWithType service) { if (service is AutofacKeyedService) { return new KeyedService { Key = ((AutofacKeyedService)service).ServiceKey, Type = ((AutofacKeyedService)service).ServiceType }; } return new TypedService { Type = service.ServiceType }; }