Registering decorators in Microsoft.Extensions.DependencyInjection: the manual inner-concrete-plus-factory approach, lifetime alignment and captive decorators, who disposes inner and outer objects, ordering of stacked decorators, open generic decoration and Scrutor's Decorate/TryDecorate.
Microsoft.Extensions.DependencyInjection has no Decorate method (unlike Autofac or Lamar), so you register the inner implementation as its concrete type (or under a key) and the interface with a factory that wraps it: AddScoped<IProductRepository>(sp => new CachingProductRepository(sp.GetRequiredService<EfProductRepository>(), ...)). Three things decide whether it's correct. Lifetimes: the decorator must not outlive its inner, or you've built a captive dependency. Disposal: the container disposes everything it created, so the decorator mustn't dispose the inner. Order: the last wrapper registered is the outermost, so I keep one concern per decorator and test the resolved chain. Scrutor's Decorate does the descriptor surgery for you, keeps the lifetime and handles many registrations at once. The trade-off is a small library dependency and start-up reflection versus hand-written factories that are explicit, which I still prefer for one or two decorators.
"The built-in container doesn't know about decorators, so I build them from two registrations. The real implementation is registered as its concrete type,
EfProductRepository, andIProductRepositoryis registered with a factory that resolves the concrete type and wraps it inCachingProductRepository. The consumer asks for the interface and gets the decorator. If I need several layers, I nest them in the factory or chain registrations, and I keep in mind that the last wrapper is the outermost: logging outside caching logs cache hits, caching outside retry caches the final result, and getting that wrong is a real bug, not a style choice.For example, at [company] we [added a caching decorator around a product repository as a singleton, because the cache was a singleton]. The inner repository depended on the scoped
DbContext, so the singleton decorator captured the first request's context. In DevelopmentValidateScopeswould have caught it, but the factory registration was only exercised in production. Under load we got ["A second operation was started on this context" errors about 40 times a minute]. The fix was making the decorator scoped and moving the cache itself into a separate singletonHybridCache. [Errors went to zero after the deploy.]Disposal is the other trap: the container disposes both objects it created, so a decorator that also disposes its inner causes double disposal. When there are many registrations to decorate, or open generics, I use Scrutor's
Decorate, which rewrites the descriptors and keeps their lifetimes. The senior point is that decorators are cheap to add, but their lifetime and order are part of the behaviour, so I test the resolved chain."
| Manual factory | Scrutor Decorate |
|
|---|---|---|
| Dependency | None | Scrutor NuGet package (7.x as of late 2026) |
| Lifetime | You choose (and can get it wrong) | Copies the decorated descriptor's lifetime |
Many implementations (IEnumerable<T>) |
One factory per registration | Decorates every matching descriptor |
| Open generics | Close each type yourself | Decorate(typeof(IRepo<>), typeof(CachingRepo<>)) over the closed registrations present |
| No matching registration | Inner resolve fails at run time | Decorate throws at start-up; TryDecorate skips |
| Native AOT | Fine if factories avoid reflection | Uses reflection; check trimming warnings |
| Inner | Allowed decorator lifetimes | Why |
|---|---|---|
| Singleton | Singleton, scoped, transient | Shorter-lived wrapper over long-lived inner is fine |
| Scoped | Scoped, transient | A singleton would capture one scope's inner |
| Transient | Transient (or scoped with care) | A longer-lived decorator pins one transient instance |
A caching decorator around a pricing repository took p95 for the catalogue endpoint from about 180 ms to 25 ms with a 92% hit rate. The win only held once we put the cache-key logic in the decorator and the cache store in a separate singleton, so the decorator itself could stay scoped like the repository.
Checks whether the candidate can wire decorators correctly in the built-in container and reason about the lifetime, disposal and ordering consequences, not just recite the pattern.
Green flags
IFoo → CachingFoo(IFoo) loopsRed flags
Decorate methodA decorator implements IFoo and needs an IFoo. If you register IFoo → CachingFoo and CachingFoo asks for IFoo, the container finds CachingFoo again and reports a circular dependency. The fix is to give the inner a different identity: its concrete type, or (in .NET 8+) a key.
Resolve IFoo
-> factory(sp)
-> sp.GetRequiredService<EfFoo>() (inner, by concrete type)
-> new CachingFoo(inner, cache)
With keyed services you can register the inner as AddKeyedScoped<IFoo, EfFoo>("inner") and the decorator takes [FromKeyedServices("inner")] IFoo. In .NET 10 a parameterless [FromKeyedServices] uses ServiceKeyLookupMode.InheritKey, so a keyed decorator can request the inner with the same key it was resolved with.
The container caches the decorator according to the decorator's registration. If that is singleton, the factory runs once on the root provider and whatever inner it resolved is held forever. With ValidateScopes on, resolving a scoped inner from the root throws; without it, you get a captive dependency. Rule: decorator lifetime ≤ inner lifetime.
The container tracks disposables it creates, including objects returned from factories. With a manual decorator both inner (resolved through the container) and decorator (returned by the factory) are tracked and disposed when their scope ends, in reverse order of creation. If the decorator's Dispose also disposes the inner, the inner is disposed twice. Most framework types tolerate that; your own may not. A decorator should only dispose resources it created itself.
Registration order: EfRepo -> Caching -> Logging
Call path: Logging -> Caching -> EfRepo
The last wrapper applied is the outermost. Typical intent: logging/metrics outermost (see everything), then caching, then retry/resilience nearest the I/O. Retry outside caching re-runs cache lookups; caching outside retry may cache a failure if errors aren't excluded.
services.Decorate<IFoo, CachingFoo>() finds every descriptor for IFoo already in the collection, and replaces each with a new descriptor of the same lifetime whose factory creates the original implementation and then the decorator around it (using ActivatorUtilities, so other constructor parameters still come from DI). Consequences: it must run after the registrations it decorates; anything registered later is not decorated; Decorate throws a DecorationException if nothing matches, TryDecorate returns false. For open generics, Scrutor decorates the matching registrations present in the collection; register closed types (for example through scanning) if your version can't decorate an open generic descriptor itself.
HttpClient handler pipelines (DelegatingHandler) are decorators wired by IHttpClientFactory, with order set by registration order of AddHttpMessageHandler. MediatR pipeline behaviours and ASP.NET Core middleware are decorators/chains with their own composition rules. Prefer those when they exist rather than decorating the container registration.
IFoo → CachingFoo where CachingFoo takes IFoo and observe the circular dependency error; then fix it with a concrete-type inner.ValidateScopes = true and read the exception.Dispose calls; end a scope and check the disposal order and count.Decorate before the inner registration and see Scrutor's DecorationException.A manual decorator with the built-in container, a keyed variant, and the Scrutor equivalent (.NET 10, Microsoft.Extensions.Caching.Hybrid):
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.DependencyInjection;
namespace Catalogue;
public sealed record Product(int Id, string Name, decimal Price);
public interface IProductRepository
{
Task<Product?> GetAsync(int id, CancellationToken ct);
}
public sealed class EfProductRepository(CatalogueDbContext db) : IProductRepository
{
public async Task<Product?> GetAsync(int id, CancellationToken ct) =>
await db.Products.FindAsync([id], ct);
}
// Scoped like its inner; the long-lived cache store is a separate singleton (HybridCache).
public sealed class CachingProductRepository(IProductRepository inner, HybridCache cache) : IProductRepository
{
public async Task<Product?> GetAsync(int id, CancellationToken ct) =>
await cache.GetOrCreateAsync($"product:{id}",
async token => await inner.GetAsync(id, token), cancellationToken: ct);
// No Dispose: the container owns and disposes the inner repository.
}
public static class CatalogueRegistration
{
public static IServiceCollection AddCatalogue(this IServiceCollection services)
{
services.AddHybridCache();
services.AddScoped<EfProductRepository>(); // inner, by concrete type
services.AddScoped<IProductRepository>(sp => // decorator, same lifetime
new CachingProductRepository(
sp.GetRequiredService<EfProductRepository>(),
sp.GetRequiredService<HybridCache>()));
return services;
}
// Alternative with keyed services: inner under a key, decorator asks for it by key.
public static IServiceCollection AddCatalogueKeyed(this IServiceCollection services)
{
services.AddHybridCache();
services.AddKeyedScoped<IProductRepository, EfProductRepository>("inner");
services.AddScoped<IProductRepository>(sp => new CachingProductRepository(
sp.GetRequiredKeyedService<IProductRepository>("inner"),
sp.GetRequiredService<HybridCache>()));
return services;
}
}
The same with Scrutor, including an open generic and explicit order:
// dotnet add package Scrutor
services.AddScoped<IProductRepository, EfProductRepository>();
services.Decorate<IProductRepository, CachingProductRepository>(); // inner -> caching
services.Decorate<IProductRepository, LoggingProductRepository>(); // outermost: sees cache hits too
// Decorates the IRepository<T> registrations already in the collection.
services.Decorate(typeof(IRepository<>), typeof(AuditingRepository<>));
// In a library: don't fail if the app didn't register the service.
services.TryDecorate<IProductRepository, MetricsProductRepository>();
IFoo → CachingFoo where CachingFoo takes IFoo. Why it is wrong: the container resolves the decorator for its own dependency and reports a circular dependency. Instead: register the inner as its concrete type or under a key.DbContext, causing stale data and concurrency exceptions. Instead: keep the decorator at the inner's lifetime and inject a singleton cache store.Dispose. Why it is wrong: the container already disposes the inner, so it's disposed twice. Instead: dispose only resources the decorator created.Decorate before the inner registration or before a library's AddX(). Why it is wrong: Scrutor only decorates descriptors already in the collection. Instead: decorate after all registrations, and test the resolved type.DelegatingHandlers and resilience pipelines; request concerns in middleware or endpoint filters. Instead: use the framework's pipeline and keep decorators for your own abstractions.new for every constructor parameter. Why it is wrong: adding a dependency to the decorator means editing the factory, and it's easy to forget. Instead: use ActivatorUtilities.CreateInstance<CachingFoo>(sp, inner) so other parameters still come from DI.Decorators are one of the best uses of DI because they add behaviour without touching the class, but in the built-in container they're hand-assembled, so they inherit every lifetime and disposal mistake you can make with factories. I keep three rules: decorator lifetime ≤ inner lifetime, the decorator never disposes what it didn't create, and the stack order is tested. Scrutor is worth the dependency once you have more than a couple of decorated services or any open generics; for one decorator, a factory is clearer.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Manual factory | One or two decorators | Hand-wiring; lifetime errors are on you | Many services or open generics |
| Keyed inner (.NET 8+) | Want interface-typed inner without concrete-type registration | Key strings | Libraries that may run on containers without keyed support |
Scrutor Decorate |
Many registrations, open generics | Library and start-up reflection | Native AOT-sensitive apps |
| Framework pipelines (DelegatingHandler, middleware, MediatR behaviours) | HTTP, request or handler concerns | Tied to that framework | Your own domain abstractions |
Measure the benefit of a caching decorator with hit-rate and latency metrics per endpoint, and the cost with a resolution benchmark if the chain is deep.
Decorator wraps an object in another object that implements the same interface, adds behaviour before or after delegating, and is invisible to callers. Decorators stack: logging around caching around the real repository. Each concern is one small class, so the original stays untouched (Open/Closed).
.NET uses it everywhere: GZipStream(BufferedStream(FileStream)), CryptoStream, and DelegatingHandler pipelines in HttpClient.
The built-in container has no Decorate method. You register the inner type concretely and the interface with a factory delegate, use a keyed inner service, or use Scrutor's Decorate<TService, TDecorator>().
The trade-off is that order matters and long chains are harder to debug.
All three symptoms come from wrapper order and duplication. The outermost decorator or handler runs first and can short-circuit everything inside it.
AddStandardResilienceHandler. The standard pipeline is already rate limiter → total timeout → retry → circuit breaker → attempt timeout.To diagnose, list the ServiceDescriptors, walk the resolved chain, inspect the handler order, and read span nesting in traces. Then compose the chain in one place and add tests that assert its order and attempt counts.
Microsoft.Extensions.DependencyInjection (still in .NET 10) can't attach a factory or decorator to an open generic, so you close it yourself. Enumerate the entity types you use (from the DbContext model or a marker interface), and for each T register the inner EfRepository<T> as its concrete type, then register IRepository<T> with a factory that builds CachingRepository<T> around it. Do the reflection (MakeGenericType, ActivatorUtilities.CreateFactory) once at start-up and cache the resulting ObjectFactory, so each resolution is a delegate call rather than reflection. The costs: start-up work proportional to the number of entity types, factory registrations that ValidateOnBuild can't inspect, and code that isn't trimming/AOT-safe. For a handful of entities, explicit closed registrations are clearer; for many, Scrutor's Decorate(typeof(IRepository<>), typeof(CachingRepository<>)) is usually the better choice.
How to tell it (STAR)
**S:** On [our catalogue API], we'd just added a caching decorator in front of the product repository. **T:** Within an hour of release we had [around 40] EF Core concurrency exceptions a minute and some stale prices, and I owned the fix. **A:** All the exceptions came through the decorator. I checked the registration and saw it was a singleton wrapping a scoped repository, so one request's `DbContext` was being shared by everyone. I rolled the registration back, then made the decorator scoped and moved the cache store into a singleton `HybridCache`. I also added an integration test that builds the host with scope validation on and resolves every service. **R:** Errors went to [zero], the cache still gave us [a 92%] hit rate, and the test has since caught [two] similar lifetime mistakes before they reached production.
Last updated 23 Nov 2026.