Repository navigation
Closed as not planned
Labels
api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-Extensions-DependencyInjectionfeature-request
Milestone
Description
AB#1244416
Currently Scrutor has these:
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:
- Performance of those methods, some of them allocate (https://github.com/khellang/Scrutor/blob/338a59333c7eafe25d5aefdd22434653c83eb9ab/src/Scrutor/ServiceCollectionExtensions.Decoration.cs#L249)
- Performance of Scanning the IServiceCollection, multiple times (https://github.com/khellang/Scrutor/blob/338a59333c7eafe25d5aefdd22434653c83eb9ab/src/Scrutor/ServiceCollectionExtensions.Decoration.cs#L294)
- Performance of service resolution https://github.com/khellang/Scrutor/blob/338a59333c7eafe25d5aefdd22434653c83eb9ab/src/Scrutor/ServiceCollectionExtensions.Decoration.cs#L333-L356,
ActivatorUtilities.GetServiceOrCreateInstanceshould be swapped withCreateFactory. - The quirks around the fact that this mutates the service collection in place (https://github.com/khellang/Scrutor/blob/338a59333c7eafe25d5aefdd22434653c83eb9ab/src/Scrutor/ServiceCollectionExtensions.Decoration.cs#L296). It affects code like this:
WorksDoes not workservices.AddSingleton<IFoo, Foo>(); services.Decorate<IFoo, Foo2>();
services.Decorate<IFoo, Foo2>(); services.AddSingleton<IFoo, Foo>();
Reacted by rcollina, Maksim Volkau, Wouter Smit, Loïc Sharma, Viacheslav Ivanov, NilFusion, Alexey Malinin, ulrichb, Cleyton Goncalves, Micah Rairdon and 37 more
Metadata
Metadata
Assignees
Labels
api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-Extensions-DependencyInjectionfeature-request
Activity
khellang commentedon Nov 13, 2019
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.
davidfowl commentedon Nov 13, 2019
I think people are wrong there, the most correct thing is to preserve the lifetime.
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.
Agreed but I think doing this without it being a container native feature is appealing.
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.
davidfowl commentedon Nov 13, 2019
cc @aspnet/di-council
seesharper commentedon Nov 14, 2019
@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
Example
Registration
Let's take a look at the following registrations.
The decorators are applied in the registration order meaning that the decorator chain here will be
Please note that service registration is completely decoupled from the decorators meaning that the following will also work.
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
davidfowl commentedon Nov 14, 2019
@seesharper See the code I linked to (@khellang's code) which implements decorators on top of the
IServiceCollectionprimitives. 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.dadhi commentedon Nov 14, 2019
@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:
ENikS commentedon Nov 14, 2019
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?
khellang commentedon Nov 14, 2019
https://en.m.wikipedia.org/wiki/Decorator_pattern
ENikS commentedon Nov 14, 2019
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?
khellang commentedon Nov 14, 2019
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.
The latter. You'll get a chain of wrapped interceptors.
ENikS commentedon Nov 14, 2019
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
ENikS commentedon Nov 14, 2019
@dadhi
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.
khellang commentedon Nov 14, 2019
The OP shows an implementation of this on top of the existing abstractions as extensions.
ENikS commentedon Nov 14, 2019
@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.
seesharper commentedon Nov 14, 2019
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.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.
To decorate each command handler with the
TransactionalCommandHandlerall we need is this line (LightInject).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
objectmeaning there will be a lot of casting and boxing going on.35 remaining items
WeihanLi commentedon Jan 23, 2026
For someone not want to integrate a library, could use the following code in your own code to support simple decorating
julealgon commentedon Jan 23, 2026
@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.
aradalvand commentedon Feb 9, 2026
Here's my implementation of
Decoratebased 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:
julealgon commentedon 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? That would be a nice way to have your implementation benefit the entire community as that is a very popular package.
aradalvand commentedon Feb 9, 2026
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.rosebyte commentedon Feb 12, 2026
Triage: the idea feels reasonable, we consider implementing it in future.
ScarletKuro commentedon Mar 18, 2026
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,
IPipelineBehavioris 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.rosebyte commentedon Jun 8, 2026
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.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.