📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you register decorators with the .NET dependency injection container? Explain the manual factory approach with the built-in container, how decorators interact with lifetimes and disposal, decoration order, decorating open generics, and when you would use Scrutor's Decorate instead.

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.

Senior Theory Advanced aspnet-core decorator-pattern dependency-injection scrutor service-lifetimes

🎯 Key points

  • Microsoft.Extensions.DependencyInjection has no Decorate API (Autofac and Lamar do): register the inner as its concrete type or under a key, and the interface with a factory that wraps it
  • A decorator's lifetime must not be longer than its inner's: a singleton decorator over a scoped inner is a captive dependency
  • The container disposes what it created; a decorator must not dispose an inner it didn't create
  • Stacked decorators: the last registered wrapper is the outermost; keep each decorator to one concern and assert the resolved chain in a test
  • Decoration must run after the inner registration; registrations added later are not decorated
  • Scrutor's Decorate replaces matching descriptors and keeps their lifetime; TryDecorate doesn't throw when nothing matches
  • Open generic decoration needs Scrutor or manual per-type closing; the built-in container can't add a factory for an open generic
  • .NET 10's parameterless [FromKeyedServices] (InheritKey) lets a keyed decorator receive the inner registered under its own key

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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, and IProductRepository is registered with a factory that resolves the concrete type and wraps it in CachingProductRepository. 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 Development ValidateScopes would 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 singleton HybridCache. [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 vs Scrutor

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

Lifetime rules for decorators

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

Production example

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.

🔍 What the interviewer is checking

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

  • Explains the concrete-type or keyed inner trick and why IFoo → CachingFoo(IFoo) loops
  • States decorator lifetime ≤ inner lifetime and gives the captive example
  • Knows the container disposes both and the decorator mustn't dispose the inner
  • Knows Scrutor's behaviour: replaces descriptors, keeps lifetimes, runs after registrations

Red flags

  • Thinks the built-in container has a Decorate method
  • Makes decorators singletons by default
  • Can't explain which decorator in a stack runs first

📚 Learn in depth

1. Why the built-in container needs a workaround

A 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.

2. Lifetimes

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.

3. Disposal

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.

4. Order

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.

5. How Scrutor does it

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.

6. Decorators elsewhere in .NET

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.

Try it yourself

  1. Register IFoo → CachingFoo where CachingFoo takes IFoo and observe the circular dependency error; then fix it with a concrete-type inner.
  2. Make the decorator a singleton over a scoped inner with ValidateScopes = true and read the exception.
  3. Add logging that prints constructor and Dispose calls; end a scope and check the disposal order and count.
  4. Stack two decorators with Scrutor in both orders and write a test asserting the outer type.
  5. Call Decorate before the inner registration and see Scrutor's DecorationException.

💻 Code

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>();

⚠ Common mistakes

  • Mistake: Registering 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.
  • Mistake: Making a caching decorator a singleton because "the cache is global". Why it is wrong: it captures a scoped inner and its DbContext, causing stale data and concurrency exceptions. Instead: keep the decorator at the inner's lifetime and inject a singleton cache store.
  • Mistake: Disposing the inner service in the decorator's Dispose. Why it is wrong: the container already disposes the inner, so it's disposed twice. Instead: dispose only resources the decorator created.
  • Mistake: Calling 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.
  • Mistake: Not thinking about the order of stacked decorators. Why it is wrong: retry outside caching, or caching outside error handling, changes behaviour (cached errors, repeated work). Instead: decide the order deliberately and assert it in a test.
  • Mistake: Using a decorator for something the framework already composes. Why it is wrong: HTTP concerns belong in DelegatingHandlers and resilience pipelines; request concerns in middleware or endpoint filters. Instead: use the framework's pipeline and keep decorators for your own abstractions.
  • Mistake: Writing a manual factory with 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.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate explains the pattern but not the registration Why: Checks the Decorator pattern itself and where .NET uses it
    How to answer

    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.

  2. When: Candidate mentions stacking decorators or HttpClient handlers Why: Checks debugging decorator and handler order in production
    How to answer

    All three symptoms come from wrapper order and duplication. The outermost decorator or handler runs first and can short-circuit everything inside it.

    • Cached errors: the cache sits outside a fallback that turns exceptions into "empty" results, so it stores the outage for the full TTL. Put the fallback outermost (Fallback → Cache → real search): exceptions pass through the cache uncached, and the empty answer is never stored.
    • Retry storms: retries in two layers multiply attempts, for example a custom handler on top of AddStandardResilienceHandler. The standard pipeline is already rate limiter → total timeout → retry → circuit breaker → attempt timeout.
    • Duplicate logs: a decorator or handler is registered twice, or a custom logging handler sits on top of the built-in HttpClient logging.

    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.

  3. When: Candidate says decorating open generics needs Scrutor Why: Checks whether they can close types manually when a library isn't allowed
    How to answer

    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.

🛠 Real-world problems: how you handle them

Singleton caching decorator captured a scoped DbContext
Situation
A [retail catalogue] API on .NET [10] serving about [1,500] requests per second added a caching decorator around `IProductRepository`. It was registered as a singleton through a factory, while the inner `EfProductRepository` and its `DbContext` were scoped. Development used an in-memory provider and rarely exercised the path.
Signals
After release, Application Insights showed `InvalidOperationException: A second operation was started on this context instance` at about [40] per minute, plus occasional `ObjectDisposedException` for the `DbContext`. Some product prices stayed stale long after updates.
Investigation
Grouped exceptions by operation and found all came through `CachingProductRepository`. Reviewed `Program.cs` and saw `AddSingleton<IProductRepository>(sp => ...)` resolving the scoped inner from the root provider. Reproduced locally with `ValidateScopes = true` in a `WebApplicationFactory` test, which threw `Cannot resolve scoped service ... from root provider`.
Resolution
Immediate: rolled back the decorator registration. Fix: made the decorator scoped, moved cache storage to the singleton `HybridCache`, and turned on `ValidateScopes` and `ValidateOnBuild` in all environments for the integration tests.
Prevention
An integration test that builds the real host with validation on and resolves every registered service type. A review checklist item: decorator lifetime ≤ inner lifetime. A dashboard alert on EF Core concurrency exceptions.

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.

↩ Usually asked after

More in Advanced DI

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me