Skip to content

Support for open generic decorators #14

Closed

Description

@yolofy

The following throws an exception (Could not find any registered services for type 'DiTest.IPrinter`2'.):

  private static void ConfigureServices(ServiceCollection services)
        {
          services.Scan(
                scan => scan.FromAssemblies(typeof(Program).GetTypeInfo().Assembly)
                    .AddClasses(x => x.AssignableTo(typeof(IPrinter<,>)))
                    .AsImplementedInterfaces()
                    .WithSingletonLifetime()
            );
            services.Decorate(typeof(IPrinter<,>), typeof(TextColorDecorator<,>));
            services.Decorate(typeof(IPrinter<,>), typeof(BackgroundColorDecorator<,>));
}

These classes where used:

   public interface IPrinter<T1, T2>
    {
        void Print(T1 arg1, T2 arg2);
    }
    public class Printer : IPrinter<string, string>
    {
        public void Print(string arg1, string arg2)
        {
            Console.WriteLine("Hi {0}, I am decoratee! {1}", arg1, arg2);
        }
    }
    public class TextColorDecorator<T1, T2> : IPrinter<T1, T2>
    {
        private readonly IPrinter<T1, T2> decoratee;

        public TextColorDecorator(IPrinter<T1, T2> decoratee)
        {
            this.decoratee = decoratee;
        }

        public void Print(T1 arg1, T2 arg2)
        {
            var originalColor = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Red;
            this.decoratee.Print(arg1, arg2);
            Console.ForegroundColor = originalColor;
        }
    }
    public class BackgroundColorDecorator<T1, T2> : IPrinter<T1, T2>
    {
        private readonly IPrinter<T1, T2> decoratee;

        public BackgroundColorDecorator(IPrinter<T1, T2> decoratee)
        {
            this.decoratee = decoratee;
        }

        public void Print(T1 arg1, T2 arg2)
        {
            var originalColor = Console.BackgroundColor;
            Console.BackgroundColor = ConsoleColor.White;
            this.decoratee.Print(arg1, arg2);
            Console.BackgroundColor = originalColor;
        }
    }

Activity

  1. khellang commented on Oct 28, 2016

    @khellang
    Owner

    Yeah, this is a limitation of Microsoft.Extensions.DependencyInjection. I've tried hard to make this work, but I can't see a way to accomplish this today. (See aspnet/DependencyInjection#450)

    The way decoration works, is that we chain factory functions. There's several problems with factory functions and open generics today:

    1. If you try to register a factory function for an open generic type, the container will throw. This is a limitation that could be removed, but that leads us to 2.
    2. In a factory function, there's no way of knowing the actual type that was requested. This is necessary, because we need to dynamically construct a generic type based on the requested types' generic arguments.

    Example

    If you have a registration:

    services.AddTransient<IService, Service>();

    When you decorate this type, using DecoratorService, it roughly translate to

    services.AddTransient<IService>(provider => new DecoratorService(provider.GetService<IService>()));

    This is not 100% true, since this would blow the stack, but for the sake of simplicity, let's just say that's how it works.

    When you resolve IService, it'll translate to

    new DecoratorService(new Service());

    However, if you add open generics into this mix, things get a bit more complicated:

    services.AddTransient(typeof(IService<>), typeof(Service<>));
    
    services.AddTransient(typeof(IService<>), provider => {
        // How can we resolve the correct type here, without knowing the generic arguments of the type that was resolved?
        return new DecoratorService<???>(provider.GetService<IService<???>>());
    });

    Do you see the problem? With open generics, you could resolve IService<> with any generic argument:

    provider.GetService<IService<string>>();
    provider.GetService<IService<int>>();
    provider.GetService<IService<MyClass>>();

    In order for us to decorate this, we need to know the generic argument, string, int and MyClass respectively, in order to construct the DecoratorService<T> type. This is information that the container clearly has, but it's not making it available anywhere today.

  2. khellang commented on Oct 28, 2016

    @khellang
    Owner

    BTW, scanning works with open generics. We already do something similar to what you linked when you call AssignableTo in your example. This limitation is only for decoration.

  3. yolofy commented on Oct 28, 2016

    @yolofy
    Author

    I don't think the following is production ready but it seems to work (I user the Decorate2 method):

    public static class CustomExtensions
    {
        public static IServiceCollection Decorate2(this IServiceCollection services, Type serviceType, Type decoratorType)
        {
            if ((object)decoratorType == null)
                throw new ArgumentNullException(nameof(decoratorType));
            return services.DecorateDescriptors(serviceType, x => x.Decorate(**serviceType**, decoratorType));
        }
    
        private static IServiceCollection DecorateDescriptors(this IServiceCollection services, Type serviceType, Func<ServiceDescriptor, ServiceDescriptor> decorator)
        {
            if (services == null)
                throw new ArgumentNullException(nameof(services));
            if (serviceType == null)
                throw new ArgumentNullException(nameof(serviceType));
            foreach (var descriptor in services.GetDescriptors(serviceType))
            {
                int index = services.IndexOf(descriptor);
                services.Insert(index, decorator(descriptor));
                services.Remove(descriptor);
            }
            return services;
        }
    
        private static List<ServiceDescriptor> GetDescriptors(this IServiceCollection services, Type serviceType)
        {
            var serviceDescriptorList = new List<ServiceDescriptor>();
            foreach (var service in services)
            {
                if (service.ServiceType == serviceType)
                {
                    serviceDescriptorList.Add(service);
                }
                **else if (service.ServiceType.IsAssignableToGenericType(typeof(IPrinter<,>)))
                {
                    serviceDescriptorList.Add(service);
                }**
            }
            if (serviceDescriptorList.Count == 0)
                throw new InvalidOperationException(
                    string.Format("Could not find any registered services for type '{0}'.", new object[]
                    {
                        serviceType.FullName
                    }));
            return serviceDescriptorList;
        }
    
        private static ServiceDescriptor Decorate(this ServiceDescriptor descriptor, **Type serviceType**, Type decoratorType)
        {
            return descriptor.WithFactory(provider => provider.CreateInstance(decoratorType, **serviceType**, provider.GetInstance(descriptor)));
        }
    
        private static ServiceDescriptor WithFactory(this ServiceDescriptor descriptor, Func<IServiceProvider, object> factory)
        {
            return ServiceDescriptor.Describe(descriptor.ServiceType, factory, descriptor.Lifetime);
        }
    
        private static object CreateInstance(this IServiceProvider provider, Type decoratorType, **Type serviceType**, object decoratee)
        {
            **var tInfo = decoratorType.GetTypeInfo();
    
            if (tInfo.GenericTypeArguments.Length != tInfo.GenericTypeParameters.Length)
            {
                var matchingInterface =
                    decoratee.GetType()
                        .GetTypeInfo()
                        .ImplementedInterfaces.First(ii => ii.IsAssignableToGenericType(serviceType));
    
                decoratorType = decoratorType.MakeGenericType(matchingInterface.GenericTypeArguments);
            }**
    
            return ActivatorUtilities.CreateInstance(provider, decoratorType, decoratee);
        }
    
        private static object GetInstance(this IServiceProvider provider, ServiceDescriptor descriptor)
        {
            if (descriptor.ImplementationInstance != null)
                return descriptor.ImplementationInstance;
            if (descriptor.ImplementationType != null)
                return provider.GetServiceOrCreateInstance(descriptor.ImplementationType);
            return descriptor.ImplementationFactory(provider);
        }
    
        private static object GetServiceOrCreateInstance(this IServiceProvider provider, Type type)
        {
            return ActivatorUtilities.GetServiceOrCreateInstance(provider, type);
        }
    }
    
    public static class AssignableExtensions
    {
        /// <summary>
        /// Determines whether the <paramref name="genericType"/> is assignable from
        /// <paramref name="givenType"/> taking into account generic definitions
        /// </summary>
        public static bool IsAssignableToGenericType(this Type givenType, Type genericType)
        {
            if (givenType == null || genericType == null)
            {
                return false;
            }
    
            return givenType == genericType
              || givenType.MapsToGenericTypeDefinition(genericType)
              || givenType.HasInterfaceThatMapsToGenericTypeDefinition(genericType)
              || givenType.GetTypeInfo().BaseType.IsAssignableToGenericType(genericType);
        }
    
        private static bool HasInterfaceThatMapsToGenericTypeDefinition(this Type givenType, Type genericType)
        {
            return givenType
              .GetInterfaces()
              .Where(it => it.GetTypeInfo().IsGenericType)
              .Any(it => it.GetGenericTypeDefinition() == genericType);
        }
    
        private static bool MapsToGenericTypeDefinition(this Type givenType, Type genericType)
        {
            return genericType.GetTypeInfo().IsGenericTypeDefinition
              && givenType.GetTypeInfo().IsGenericType
              && givenType.GetGenericTypeDefinition() == genericType;
        }
    }
    
  4. yolofy commented on Oct 28, 2016

    @yolofy
    Author

    Side note: this code does require the decoratee (Printer) to be closed

  5. khellang commented on Oct 28, 2016

    @khellang
    Owner

    Hmm. I just ran the following test using the code above:

    [Fact]
    public void CanDecorateOpenGenericType()
    {
        var provider = ConfigureProvider(services =>
        {
            services.AddSingleton(typeof(IDecoratedService<>), typeof(Decorated<>));
    
            services.Decorate(typeof(IDecoratedService<>), typeof(Decorator<>));
        });
    
        var instance = provider.GetRequiredService<IDecoratedService<string>>();
    
        var decorator = Assert.IsType<Decorator<string>>(instance);
    
        Assert.IsType<Decorated<string>>(decorator.Inner);
    }

    And it fails with the following message:

    Open generic service type 'Scrutor.Tests.DecorationTests+IDecoratedService`1[T]' requires registering an open generic implementation type.

    I think this is the first limitation I mentioned above.

  6. yolofy commented on Oct 28, 2016

    @yolofy
    Author

    It will work when you decoratee is closed (e.g. Decoratedimplements IDecoratedService<string>)

  7. added this to the v2.0.0 milestone on Apr 28, 2017
  8. khellang commented on Apr 28, 2017

    @khellang
    Owner

    This should be closed with #25 and released as part of v2.0.0 ✨

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions