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

πŸ“š Interview question

What is the Decorator pattern? Explain how it adds behaviour such as caching, logging or retry without changing the original class, where .NET uses it (Stream wrappers, DelegatingHandler), and how you register decorators with the built-in DI container.

Decorator intent and structure, composition-based stacking, .NET examples (BufferedStream, GZipStream, CryptoStream, DelegatingHandler pipelines), registering decorators with factory delegates, keyed services or Scrutor, ordering, and decorators vs inheritance, middleware and AOP.

Intermediate Theory Intermediate cross-cutting-concerns decorator delegatinghandler dependency-injection design-patterns open-closed

🎯 Key points

  • Decorator implements the same interface as the component it wraps and adds behaviour before/after delegating; clients can't tell the difference
  • Decorators stack at run time (logging → caching → repository), avoiding a subclass per combination; each keeps one responsibility and is testable with a fake inner
  • Stream wrappers: new GZipStream(new BufferedStream(fileStream), ...) each add one behaviour; CryptoStream adds encryption
  • DelegatingHandler is a decorator over HttpMessageHandler; AddHttpMessageHandler registers them outermost-first
  • Built-in DI has no Decorate method: register the inner type concretely and the interface with a factory delegate, use keyed services for the inner, or use Scrutor's Decorate<TService, TDecorator>()
  • Order matters because an outer decorator can short-circuit: a cache hit returns before inner logging, authorisation or tenant filtering ever run
  • Decorators keep the Open/Closed Principle: new concerns are new classes, the original is untouched
  • Cost: an extra object and interface call per layer (usually devirtualised and negligible), but long implicit chains give deep stack traces and are hard to debug

⏱ 30-second 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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"Decorator adds behaviour to an object by wrapping it, not by changing it or subclassing it. The decorator implements the same interface as the thing it wraps, does something before or after calling the inner object, and the caller can't tell. The wrapper and the wrapped share a type, so you can stack them: a logging decorator around a caching decorator around the real repository. Each concern is a tiny class with one job, and adding a new one doesn't touch the others. That's Open/Closed in practice.

.NET is built on this. Stream is the textbook case: new GZipStream(new BufferedStream(fileStream), CompressionLevel.Optimal) gives you compression over buffering over a file, and CryptoStream adds encryption the same way. In HttpClient, every DelegatingHandler is a decorator over the next handler, which is how logging, auth headers and the resilience handler plug in. In my own code I use decorators for caching, metrics, retries around non-HTTP dependencies, and authorisation checks.

The catch is registration. The built-in container has no Decorate method. Without a library, I register the concrete inner type and then register the interface with a factory delegate that builds the decorator around it, or I register the inner as a keyed service and inject it with [FromKeyedServices]. Scrutor's services.Decorate<IProductRepository, CachedProductRepository>() does this in one line. The mistake I see is getting the order wrong, for example caching outside authorisation so one user's cached result is served to another. A decorator is only as correct as its position in the chain."


Structure

Role Example
Component (interface) IProductRepository, Stream, HttpMessageHandler
Concrete component SqlProductRepository, FileStream, SocketsHttpHandler
Decorator CachedProductRepository, GZipStream, DelegatingHandler

Decorator vs alternatives

Approach Adds behaviour by Good for Weakness
Decorator Wrapping one interface Per-service concerns (cache, metrics) Needs an interface; registration plumbing
Inheritance Overriding One fixed variation Subclass per combination; fragile base class
Middleware / DelegatingHandler Framework pipeline HTTP-wide concerns Only for that pipeline
MediatR-style pipeline behaviours Generic wrapper per request type All handlers at once Indirection, library dependency
AOP / dynamic proxy Runtime-generated wrappers Many interfaces at once Magic, harder to debug

Registration options with built-in DI

Option How Trade-off
Factory delegate AddScoped<Inner>() + AddScoped<IRepo>(sp => new Decorator(sp.GetRequiredService<Inner>(), ...)) Explicit; manual constructor wiring
Keyed inner AddKeyedScoped<IRepo, Inner>("inner") + decorator takes [FromKeyedServices("inner")] IRepo Container builds the decorator; key string
Scrutor services.Decorate<IRepo, Decorator>() One line; extra package, order = call order

Production example

A product catalogue API wrapped IProductRepository with a caching decorator and a metrics decorator. Cache hit rate reached about 92%, database CPU fell from 70% to 20%, and the repository itself didn't change. Later the caching decorator was accidentally registered outside a tenant-filtering decorator, so cached products crossed tenants. Fixing the order and adding a test that asserts the decorator chain prevented it recurring.

πŸ” What the interviewer is checking

Checks understanding of composition over inheritance and practical DI skills in .NET.

Green flags

  • Explains same-interface wrapping and stacking.
  • Names Stream wrappers and DelegatingHandler.
  • Knows the built-in container lacks Decorate and shows a working registration.
  • Brings up ordering and lifetimes.

Red flags

  • Uses inheritance for every variation.
  • Registers the decorator in a way that is circular.
  • Confuses Decorator with Adapter (changing the interface).

πŸ“š Learn in depth

1. Structure

Client ──▢ Β«interfaceΒ» IComponent
               + Operation()
            β–²                β–²
   ConcreteComponent      Decorator ── inner: IComponent
                          Operation() { before(); inner.Operation(); after(); }
                              β–²               β–²
                   LoggingDecorator   CachingDecorator

Runtime chain:  Logging ──▢ Caching ──▢ SqlRepository

2. Why not inheritance

With inheritance, three optional concerns (cache, log, metrics) need up to 2Β³ = 8 subclasses, fixed at compile time. Decorators compose at run time: three classes, any combination, any order.

3. Streams

Stream has a big virtual surface (Read, Write, ReadAsync, Flush, Dispose…). Each wrapper overrides it and forwards to the inner stream:

GZipStream ──▢ BufferedStream ──▢ FileStream ──▢ OS file handle
(compress)      (batch writes)      (syscalls)

Disposing the outer stream flushes and disposes the inner one by default (leaveOpen: false). Forgetting to dispose the outermost wrapper loses the compressed trailer.

4. DelegatingHandler

HttpClient sends through a chain of HttpMessageHandlers. Each DelegatingHandler has an InnerHandler and overrides SendAsync. With IHttpClientFactory, AddHttpMessageHandler<T>() adds handlers outermost first, so the first registered runs first on the way out and last on the way back. AddStandardResilienceHandler() adds a handler containing rate limiter, total timeout, retry, circuit breaker and attempt timeout.

5. How Scrutor's Decorate works

It finds the existing ServiceDescriptor for TService, replaces it with a new descriptor whose factory creates TDecorator, and passes the original implementation (built from the old descriptor) into the decorator's constructor. It keeps the original lifetime. Calling Decorate twice gives decorator 2 wrapping decorator 1 wrapping the original, so the last call is outermost.

6. Costs

Each layer is one extra object per resolution and one interface call per operation, which is nanoseconds and often devirtualised by the JIT in .NET 10 with dynamic PGO. The real cost is cognitive: stack traces get longer and the chain is defined in Program.cs, not visible from the class.

Try it yourself

  1. Write TimingRepository and CachedRepository decorators and register them both orders; log which runs first.
  2. Build a DelegatingHandler that adds a correlation ID header and another that logs; check the order with AddHttpMessageHandler.
  3. Forget to dispose a GZipStream and try to decompress the file.
  4. Write a test that resolves IProductRepository and asserts the runtime type chain (outer decorator first).

πŸ’» Code

Two decorators over one interface, plus three ways to register them:

namespace Catalogue;

using System.Diagnostics;

public interface IProductRepository
{
    Task<Product?> GetAsync(int id, CancellationToken ct);
}

public sealed class SqlProductRepository(AppDbContext db) : IProductRepository
{
    public Task<Product?> GetAsync(int id, CancellationToken ct) =>
        db.Products.AsNoTracking().FirstOrDefaultAsync(p => p.Id == id, ct);
}

// Decorator: same interface, adds timing, delegates to inner
public sealed class TimedProductRepository(IProductRepository inner, ILogger<TimedProductRepository> logger) : IProductRepository
{
    public async Task<Product?> GetAsync(int id, CancellationToken ct)
    {
        long start = Stopwatch.GetTimestamp();
        try
        {
            return await inner.GetAsync(id, ct);
        }
        finally
        {
            logger.LogDebug("GetAsync({Id}) took {Elapsed} ms", id, Stopwatch.GetElapsedTime(start).TotalMilliseconds);
        }
    }
}
// Program.cs: three ways to register the chain Timed -> Sql

// 1. Factory delegate (no packages)
builder.Services.AddScoped<SqlProductRepository>();
builder.Services.AddScoped<IProductRepository>(sp => new TimedProductRepository(
    sp.GetRequiredService<SqlProductRepository>(),
    sp.GetRequiredService<ILogger<TimedProductRepository>>()));

// 2. Keyed inner (.NET 8+): the container builds the decorator
// public sealed class TimedProductRepository([FromKeyedServices("inner")] IProductRepository inner, ...)
// builder.Services.AddKeyedScoped<IProductRepository, SqlProductRepository>("inner");
// builder.Services.AddScoped<IProductRepository, TimedProductRepository>();

// 3. Scrutor: last Decorate call is outermost
// builder.Services.AddScoped<IProductRepository, SqlProductRepository>();
// builder.Services.Decorate<IProductRepository, TimedProductRepository>();
// Framework decorators: Stream wrappers and DelegatingHandler
namespace Catalogue;

public sealed class CorrelationIdHandler(IHttpContextAccessor accessor) : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
    {
        if (accessor.HttpContext?.TraceIdentifier is { } id)
            request.Headers.TryAddWithoutValidation("X-Correlation-Id", id);
        return base.SendAsync(request, ct);   // delegate to the inner handler
    }
}

// builder.Services.AddTransient<CorrelationIdHandler>();
// builder.Services.AddHttpClient<PricingClient>()
//     .AddHttpMessageHandler<CorrelationIdHandler>()   // outermost
//     .AddStandardResilienceHandler();                  // inside it

⚠ Common mistakes

  • Mistake: Subclassing to add caching or logging. Why it is wrong: Each combination needs a subclass and the base class becomes fragile. Instead: Wrap with decorators that share the interface.
  • Mistake: Registering the decorator with AddScoped<IRepo, Decorator>() when the decorator also takes IRepo. Why it is wrong: The container resolves the decorator for its own dependency: a circular dependency exception. Instead: Use a factory delegate, a keyed inner, or Scrutor.
  • Mistake: Getting the order wrong (cache outside tenant or authorisation checks). Why it is wrong: Cached results bypass checks and can cross users or tenants. Instead: Decide the order deliberately and assert it in a test.
  • Mistake: A decorator that changes the contract (throws where the inner returned null, or swallows errors). Why it is wrong: Callers relying on the interface's behaviour break (Liskov). Instead: Preserve semantics; add behaviour around them.
  • Mistake: Decorating with a different lifetime than the inner (singleton decorator around a scoped repository). Why it is wrong: Captive dependency. Instead: Match lifetimes; Scrutor keeps the original lifetime.
  • Mistake: Forgetting to forward every member (only Read, not ReadAsync, in a custom Stream decorator). Why it is wrong: Some calls bypass the added behaviour or fall back to slow defaults. Instead: Override all relevant members, especially async and span-based overloads.
  • Mistake: Decorating everything "just in case". Why it is wrong: Long invisible chains make debugging hard. Instead: Add a decorator when a real cross-cutting need exists.

πŸ› Senior insight: trade-offs

Decorator is the pattern I use most in .NET services because cross-cutting concerns (caching, metrics, authorisation, retry for non-HTTP dependencies) keep turning up. The framework already gives you decorator pipelines for HTTP (DelegatingHandler, middleware), so I use custom decorators for application interfaces only.

Option When it fits Cost When not to
Custom decorator One or a few interfaces need a concern One class per concern per interface Dozens of interfaces need the same concern
DelegatingHandler Outgoing HTTP Framework plumbing Non-HTTP calls
Middleware / endpoint filters Incoming HTTP Applies broadly Per-dependency concerns
Generic pipeline behaviour Every command/query handler Library or generic plumbing Small apps
Dynamic proxy / interceptors Many interfaces, uniform concern Runtime magic Teams new to it, AOT targets

I make the chain explicit and test it: a test that resolves the service and asserts the decorator order catches a registration change that would otherwise ship silently.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate says decorators are composition rather than inheritance Why: Checks composition and delegation fundamentals
    How to answer

    Composition means a class has other objects as parts and delegates work to them, instead of inheriting behaviour. A Car has an Engine and Wheels; an OrderProcessor has a validator, a pricer and a notifier. In the strict UML sense, composition also means ownership: the parts are created and destroyed with the whole and are not shared. Benefits: behaviour can be swapped (pass a different IPricingStrategy), combined freely (decorators wrap each other), tested in isolation, and changed without a fragile base class. The cost is a little more wiring, usually handled by constructors or dependency injection.

  2. When: Candidate says decorators add behaviour without modifying the class Why: Checks Open/Closed applied pragmatically
    How to answer

    The Open/Closed Principle says modules should be open for extension but closed for modification: you add new behaviour by adding code, not by editing tested code. In C# this usually means a strategy interface with one implementation per variant, registered in DI, so adding a new payment method is a new class rather than another case in a growing switch. I apply it where change actually happens repeatedly. A small, stable switch (or a switch expression over a closed set) is fine; building extension points for variants that never arrive is speculative generality.

  3. When: Candidate gives caching as a decorator example Why: Checks writing a correct caching decorator with keys and invalidation
    How to answer

    The decorator implements IProductRepository and reads through HybridCache.GetOrCreateAsync, sending misses to the inner repository. HybridCache gives an in-memory L1 cache, an optional distributed L2, and stampede protection: 500 concurrent misses for a key make one database call.

    • Keys include everything that changes the result: product:v1:{tenant}:{id}.
    • Writes go through the decorator and invalidate after the inner write succeeds.
    • Exceptions aren't cached. Caching null is a deliberate choice with a short TTL.

    Register it with a factory delegate or a keyed inner service, or use Scrutor's Decorate<,>(). The trade-off is staleness: choose the TTL from how stale the business can tolerate.

↩ Usually asked after

More in Structural Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me