Skip to content

Add decorator extension methods to IServiceCollection #36021

Closed as not planned
Closed as not planned

Description

@davidfowl

AB#1244416
Currently Scrutor has these:

https://github.com/khellang/Scrutor/blob/338a59333c7eafe25d5aefdd22434653c83eb9ab/src/Scrutor/ServiceCollectionExtensions.Decoration.cs#L10

I think we should consider adding something similar in the box for a couple of reasons:

  • It helps when default implementations are internal or non virtual.
  • It promotes composition over inheritance

This needs to be built in a way that doesn't require container authors to change anything (that's why extension methods are being proposed).

cc @khellang Since he may want to contribute this 😉.

Some things I am concerned about in the above implementation:

Activity

  1. khellang commented on Nov 13, 2019

    @khellang
    Member

    Yeah... The current implementation is a giant hack around the container's current limitations and there are some confusing aspects around the API, like "what lifetime should the decorator have?". I've settled on copying the lifetime of the decoratee, but some people have argued that there are cases where this isn't the best solution.

    Agreed on all the perf concerns. I've basically just kept things as simple as possible (code-wise) since it's mostly a one-time cost at startup and no one has complained (yet).

    Most of them should be pretty easy to fix, i.e. remove LINQ usage, but some things are just fundamentally hard to do on top of the current feature set. I'd be really interested in hearing your take on the last bullet point, as an example.

  2. davidfowl commented on Nov 13, 2019

    @davidfowl
    MemberAuthor

    Yeah... The current implementation is a giant hack around the container's current limitations and there are some confusing aspects around the API, like "what lifetime should the decorator have?". I've settled on copying the lifetime of the decoratee, but some people have argued that there are cases where this isn't the best solution.

    I think people are wrong there, the most correct thing is to preserve the lifetime.

    Agreed on all the perf concerns. I've basically just kept things as simple as possible (code-wise) since it's mostly a one-time cost at startup and no one has complained (yet).

    People wouldn't complain but I would 😄. More seriously, we're been taking a look at how much time we spend re-enumerating the IServiceCollection at startup and it's kinda crazy.

    Most of them should be pretty easy to fix, i.e. remove LINQ usage, but some things are just fundamentally hard to do on top of the current feature set.

    Agreed but I think doing this without it being a container native feature is appealing.

    I'd be really interested in hearing your take on the last bullet point, as an example.

    I think that limitation is fine. The alternatives I can think of have to do with storing that list of decorators in a side object and writing a custom IServiceProviderFactory that unwraps them but that seems like overkill.

  3. davidfowl commented on Nov 13, 2019

    @davidfowl
    MemberAuthor

    cc @aspnet/di-council

  4. seesharper commented on Nov 14, 2019

    @seesharper

    @aspnet/di-council
    Better decorator support would be great to have and this is something that has been supported in LightInject since the beginning.

    To get the discussion going I'll give you a brief explanation of how this is implemented in LightInject.

    Decorator characteristics

    • Decorators MUST implement the same interface as the service being decorated.
    • Decorators MUST inject the service being decorated.
    • Decorators can OPTIONALLY inject other services.
    • Decorators ALWAYS follow the same lifetime/lifecycle as the decorated service (decoratee).
    • Decorators are ALWAYS applied in their registration order.

    Example

    public class FooDecorator : IFoo
    {
        public FooDecorator(IFoo decoratee, IBar bar)
        {
        }
    }

    Registration

    Let's take a look at the following registrations.

    container.RegisterScoped<IFoo, Foo>();
    container.Decorate<IFoo, FooDecorator>();
    container.Decorate<IFoo, AnotherFooDecorator>();

    The decorators are applied in the registration order meaning that the decorator chain here will be

    AnotherFooDecorator -> FooDecorator -> Foo
    

    Please note that service registration is completely decoupled from the decorators meaning that the following will also work.

    container.Decorate<IFoo, FooDecorator>();
    container.Decorate<IFoo, AnotherFooDecorator>();
    container.RegisterScoped<IFoo, Foo>();

    Lifetime

    Decorators follow the same lifetime as the service being decorated which is a very important aspect of decorators. Allowing a decorator to have a different lifetime/lifecycle than the service being decorated could lead to some serious confusion among users. If we think of decorators as being the manifestation of the Open/Closed principle, we want to be able to add new functionality/aspect without altering the behavor of the service being decorated.

    If in any case we should require different lifetimes, and mind that these cases should be extremely rare, we can always do "manual" decoration in the factory delegate used during registration. So my advice here is to keep it simple and let decorators follow the lifetime of the decorated service.

    Summary

    This covers the very basics of decorator support in LightInject and I have intentionally not gone into more advanced scenarios like decorating open generic types which is where things really starts to get complicated from an implementation standpoint. I would also advice against such advanced features as it would make it substantially harder to confirm to the MS.DI abstraction

  5. davidfowl commented on Nov 14, 2019

    @davidfowl
    MemberAuthor

    @seesharper See the code I linked to (@khellang's code) which implements decorators on top of the IServiceCollection primitives. I'm entertaining this approach because it doesn't require any changes to the spec or other containers. It's built on top but comes with some limitations.

  6. dadhi commented on Nov 14, 2019

    @dadhi

    @davidfowl ,

    If the Decorators implemented externally as extensions, does it mean that DI adapters treat them as normal services and register as usual?
    As a result we are getting two types of decorators - black boxes in the ServiceCollection and the native ones in IoC libraries.

    It may cause a confusion:

    • Both Decorartor kinds will have a different feature set.
    • Registration intent is erased in case of SC.
    • Resolution Error messages may be confusing with the mixed stack of things.
  7. ENikS commented on Nov 14, 2019

    @ENikS
    Contributor

    Could you provide a link to the relevant documentation? This term is rather ambiguous and would be nice to know exactly what is being discussed.

    Is this akin to interception?

  8. ENikS commented on Nov 14, 2019

    @ENikS
    Contributor

    So, essentially decorators are what Unity and Castle call interception, or are these separate services?

    In other words, if I resolve IFoo, will container return three services with two of them being decorators, or it will return one latest decorator with others and original service chained down the line?

  9. khellang commented on Nov 14, 2019

    @khellang
    Member

    So, essentially decorators are what Unity and Castle call interception, or are these separate services?

    I'm not super familiar with it, but I always thought interception was some sort of AOP thing where proxies were generated to intercept calls to resolved instances. I guess you could look at it as interception, but with way less magic.

    In other words, if I resolve IFoo, will container return three services with two of them being decorators, or it will return one latest decorator with others and original service chained down the line?

    The latter. You'll get a chain of wrapped interceptors.

  10. ENikS commented on Nov 14, 2019

    @ENikS
    Contributor

    Well, if this is the later than it would be rather challenging to implement for multiple, chained decorators. Not impossible, but very challenging. At present Unity does not implement multilevel interception.

    I like the idea though

  11. ENikS commented on Nov 14, 2019

    @ENikS
    Contributor

    @dadhi

    If the Decorators implemented externally as extensions, does it mean that DI adapters treat them as normal services and register as usual?

    I do not think you could register decorators as normal services. The adapter has to recognize these registrations are decorators and create relevant internal registrations (configure interception in case of Unity). The entry in a collection should unambiguously identify it as a decorator.

  12. khellang commented on Nov 14, 2019

    @khellang
    Member

    I do not think you could register decorators as normal services.

    The OP shows an implementation of this on top of the existing abstractions as extensions.

  13. ENikS commented on Nov 14, 2019

    @ENikS
    Contributor

    @khellang

    I was talking about implementing decoration in the container itself. Done at the container level it would eliminate all these scans and speed things up a bit.

  14. seesharper commented on Nov 14, 2019

    @seesharper

    Is this akin to interception?

    You could say that decorators are a way of implementing AOP (Aspect Oriented Programming) where each decorator is responsible for an "aspect" such as logging, profiling ,caching, circuit breaking and other cross cutting concerns. The decorator pattern really starts to shine when dealing with reusable open generic types. As an example, a common way of implementing the command part of the CQRS pattern is to have an ICommandHandler<T> interface like this.

    public interface ICommandHandler<in TCommand>
    {              
        Task HandleAsync(TCommand command, CancellationToken cancellationToken = default);
    }
    public class SaveCustomerCommandHandler : ICommandHandler<SaveCustomerCommand>
    {
        private readonly IDbConnection dbConnection;
        
        public SaveCustomerCommandHandler(IDbConnection dbConnection)
        {
            this.dbConnection = dbConnection;    
        }
    
        public async Task HandleAsync(SaveCustomerCommand command, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Save the customer to the database
        }
    }

    Now let's imagine that we have many of these command handlers and we want to make sure that we execute them in the context of a transaction. We could start the transaction in each command handler or we could use the decorator pattern to wrap all command handlers in a transaction like this.

    public class TransactionalCommandHandler<TCommand> : ICommandHandler<TCommand>
    {
        private readonly IDbConnection dbConnection;
        private readonly ICommandHandler<TCommand> commandHandler;    
    
        public TransactionalCommandHandler(IDbConnection dbConnection, ICommandHandler<TCommand> commandHandler)
        {
            this.dbConnection = dbConnection;
            this.commandHandler = commandHandler;        
        }
    
        public async Task HandleAsync(TCommand command, CancellationToken cancellationToken)
        {        
            using (var transaction = dbConnection.BeginTransaction())
            {
                await commandHandler.HandleAsync(command, cancellationToken);
                transaction.Commit();     
            }
        }
    }

    To decorate each command handler with the TransactionalCommandHandler all we need is this line (LightInject).

    container.Decorate(typeof(ICommandHandler<>), typeof(TransactionalCommandHandler<>))

    And Viola, all command handlers are now executed in a transaction. We could do the same for logging, profiling and other cross cutting concerns. @khellang You can decorate open generics in Scrutor as well?

    But as mentioned, most people think of AOP as magic stuff involving generating proxies and implementing interceptors. I have a fair bit of experience with how much magic it takes since I've written an interception library (LightInject.Interception). The difference is that the "decorator" is implemented at runtime (proxy) and the method calls are forwarded to the interceptor. The downside of this is that it is in many cases difficult to debug and to grasp for new developers. We will also take a performance hit since all method arguments are passed to the interceptor as object meaning there will be a lot of casting and boxing going on.

  15. 35 remaining items

  16. WeihanLi commented on Jan 23, 2026

    @WeihanLi
    Contributor

    For someone not want to integrate a library, could use the following code in your own code to support simple decorating

    public static IServiceCollection Decorate<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TDecorator>(this IServiceCollection services)
         where TService : class
         where TDecorator : class, TService
    {
        return services.Decorate(typeof(TService), typeof(TDecorator));
    }
    
    public static IServiceCollection Decorate(this IServiceCollection services, Type serviceType,
        [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type decoratorType)
    {
        var service = services.LastOrDefault(x => x.ServiceType == serviceType) ?? throw new InvalidOperationException("The service is not registered, service need to be registered before decorating");
        var objectFactory = ActivatorUtilities.CreateFactory(decoratorType, [serviceType]);
        var decoratorService = new ServiceDescriptor(serviceType, sp => objectFactory(sp, new[]
        {
            sp.CreateInstance(service)
        }), service.Lifetime);
    
        services.Replace(decoratorService);
        return services;
    }
    
    private static object CreateInstance(this IServiceProvider services, ServiceDescriptor descriptor)
    {
        if (descriptor.ImplementationInstance != null)
            return descriptor.ImplementationInstance;
    
        if (descriptor.ImplementationFactory != null)
            return descriptor.ImplementationFactory(services);
    
        return ActivatorUtilities.GetServiceOrCreateInstance(services, descriptor.ImplementationType!);
    }
  17. julealgon commented on Jan 23, 2026

    @julealgon

    @julealgon
    but that's not up to the language/API surface to decide for the developer.
    [..]
    You can argue that this could lead people into bad patterns, but I don't think that is relevant here

    There's a mantra that's sometimes used which is applicable here: making your devs fall into the pit of success.

    Introducing an API that allows them to have a decorator use a lifetime different from the thing it's decorating (and effectively alter its lifetime) is a lower friction, but ultimately incorrect, way of doing things. Rather than nudging them towards the pit of success - you'd be nudging them towards the pit of doom.

    @rjgotten I disagree with you that this is always bad and thus should be blocked at an API level. IMHO, doing that is a mistake. The library should not be opinionated to that level on something that has nuance, such as this situation.

    In addition to that, the opposite can also make sense: having a decorator that has a shorter lifetime than its decoratee.

  18. aradalvand commented on Feb 9, 2026

    @aradalvand

    Here's my implementation of Decorate based on the new keyed services functionality.

    I was initially looking to use Scrutor but it turned out that it doesn't support open generics, which was essential for my use case. So, I came up with an implementation that does — it may be useful to some of you:

    // Program.cs:
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.DependencyInjection.Extensions;
    
    var services = new ServiceCollection();
    
    services.TryAddSingleton<IFooService, FooService>();
    services.TryDecorate<IFooService, FooServiceDecorator>();
    
    services.TryAddSingleton(typeof(IBarService<>), typeof(BarService<>));
    services.TryDecorate(typeof(IBarService<>), typeof(BarServiceDecorator<>));
    
    var serviceProvider = services.BuildServiceProvider();
    var fooService = serviceProvider.GetRequiredService<IFooService>(); // Resolved as `FooServiceDecorator`
    var barService = serviceProvider.GetRequiredService<IBarService<string>>(); // Resolved as `BarServiceDecorator
    Console.WriteLine(fooService.GetType().Name); // Outputs `FooServiceDecorator`
    Console.WriteLine(barService.GetType().Name); // Outputs `BarServiceDecorator<string>`
    
    public interface IFooService;
    public interface IBarService<T>;
    
    public class FooService : IFooService;
    public class FooServiceDecorator(
        [DecorateeOf(typeof(FooServiceDecorator))]
        IFooService underlyingService
    ) : IFooService;
    
    public class BarService<T> : IBarService<T>;
    public class BarServiceDecorator<T>(
        [DecorateeOf(typeof(BarServiceDecorator<>))]
        IBarService<T> underlyingService
    ) : IBarService<T>;
    
    public static class DecorationServiceCollectionExtensions
    {
        public static string GetDecorateeKey(Type decorator) =>
            $"DECORATEE:{decorator.FullName}";
    
        extension(IServiceCollection services)
        {
            public IServiceCollection TryDecorate<TService, TDecorator>()
                where TService : class
                where TDecorator : TService
                => services.TryDecorate(typeof(TService), typeof(TDecorator));
    
            public IServiceCollection TryDecorate(
                Type serviceType,
                Type decoratorType
            )
            {
                if (services.Any(s =>
                    s.ServiceType == serviceType &&
                    (s.IsKeyedService ? s.KeyedImplementationType : s.ImplementationType) == decoratorType
                ))
                    return services;
    
                // NOTE: Whenever `serviceType` is decorated:
                // NOTE: 1. We take the last registration for it by this point:
                var decoratedService = services.Last(d => d.ServiceType == serviceType);
    
                // NOTE: 2. We replace it with a keyed variant, where the key indicates the type that decorates it (i.e. `decoratorType`). This will be the service descriptor the decorator would resolve the decorated service from at runtime.
                services.Remove(decoratedService);
    
                var key = GetDecorateeKey(decoratorType);
                var decoratedServiceAsKeyed = decoratedService.ImplementationInstance is not null
                    ? ServiceDescriptor.KeyedSingleton(
                        serviceType: decoratedService.ServiceType,
                        serviceKey: key,
                        implementationInstance: decoratedService.ImplementationInstance!
                    )
                    : decoratedService.ImplementationFactory is not null
                        ? ServiceDescriptor.DescribeKeyed(
                            serviceType: decoratedService.ServiceType,
                            serviceKey: key,
                            implementationFactory: (sp, _) => decoratedService.ImplementationFactory(sp),
                            lifetime: decoratedService.Lifetime
                        )
                        : ServiceDescriptor.DescribeKeyed(
                            serviceType: decoratedService.ServiceType,
                            serviceKey: key,
                            implementationType: decoratedService.ImplementationType!,
                            lifetime: decoratedService.Lifetime
                        );
                services.Add(decoratedServiceAsKeyed);
    
                // NOTE: 3. Finally, we add the decorator itself, which will act as the canonical registration for `serviceType` from here on.
                var decoratorService = ServiceDescriptor.Describe(
                    serviceType: decoratedService.ServiceType,
                    implementationType: decoratorType,
                    lifetime: decoratedService.Lifetime
                );
                services.Add(decoratorService);
    
                return services;
            }
        }
    }
    
    public sealed class DecorateeOf(Type decoratorType) : FromKeyedServicesAttribute(
        key: DecorationServiceCollectionExtensions.GetDecorateeKey(decoratorType)
    );
  19. julealgon commented on Feb 9, 2026

    @julealgon

    @aradalvand if you've found a nice way to support open generics, have you considered proposing it as a feature in Scrutor itself? That would be a nice way to have your implementation benefit the entire community as that is a very popular package.

  20. aradalvand commented on Feb 9, 2026

    @aradalvand

    if you've found a nice way to support open generics, have you considered proposing it as a feature in Scrutor itself?

    I have; the problem is that my approach requires using an extra attribute [DecorateeOf] within the decorators, which would be a breaking change in Scrutor. My solution is just a fundamentally different design not compatible with Scrutor's, since Scrutor was built before keyed services were a thing in standard .NET.

  21. rosebyte commented on Feb 12, 2026

    @rosebyte
    Member

    Triage: the idea feels reasonable, we consider implementing it in future.

  22. ScarletKuro commented on Mar 18, 2026

    @ScarletKuro

    My two cents. Any DI container needs first-class decorator support. It’s so essential that it’s surprising it’s still missing. Even in MediatR, IPipelineBehavior is essentially a decorator if you look at how it’s implemented and used. I still use SimpleInjector on top of Microsoft DI because of how often I rely on decorators and how well they work there. I’d happily use Scrutor, but as mentioned above, it doesn’t support open generics, without that, it’s useless for me.

  23. added
    in-pr
    on Apr 29, 2026
  24. removed
    in-pr
    on Apr 30, 2026
  25. self-assigned this
    on May 28, 2026
  26. modified the milestones: Future, 11.0.0 on Jun 8, 2026
  27. rosebyte commented on Jun 8, 2026

    @rosebyte
    Member

    The decorator semantics users actually expect, and that every container with first-class decorator support (Autofac, LightInject, DryIoc, SimpleInjector, Lamar, etc.) provides, are resolution-time: register the decorator once, applies to all current and future matching registrations, works for open generics, applies to every element of IEnumerable. None of that can be expressed on top of IServiceCollection alone, because the container only sees plain ServiceDescriptors at build time.
    Delivering those semantics from MSDI would require a new descriptor shape that every container adapter must recognise. That's a spec change with no good outcome: third-party containers either break (and the application can't use the library any more), or silently ignore the decoration, in which case libraries that rely on it end up with behaviour that isn't happening.

    What we could ship is a more honest, narrower convenience Wrap<T>(...). It reads the existing registration for a service and adds a new descriptor that constructs a wrapper around it. Same lifetime as the wrapped registration. It is explicitly a one-shot override, not a standing rule, no open generics, no IEnumerable magic, later Add/Replace for the same service overrides it.

    services.Wrap<IFoo>((sp, inner) => new FooLogging(inner, sp.GetRequiredService<ILogger<FooLogging>>()));

    This covers the common application-composition cases (log/cache/measure a service I just registered) and stays true for libraries. Libraries should register positive contributions, not "wrap whatever the consumer registers after me". Resolution-time decorator semantics would encourage the latter.

    That said, Wrap can be implemented entirely on top of the existing public API of MEDI and MEDI.Abstractions: no internals are needed. Scrutor already ships most of it; the only thing it's missing is the keyed overloads, which only became expressible once IServiceCollection got keyed-services support. So anyone who wants this today can write it as a small helper or take a community package.

    Given that, we don't see a strong reason to add Wrap in-box right now. We'll reconsider if a concrete use case shows up that's blocked from using a third-party implementation, for example a compliance environment where pulling in non-Microsoft packages isn't an option, or where the lack of a "blessed shape" is causing real interop pain across libraries.

  28. locked and limited conversation to collaborators on Jul 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

api-suggestionarea-Extensions-DependencyInjectionfeature-request

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions