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.
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.
"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.
Streamis the textbook case:new GZipStream(new BufferedStream(fileStream), CompressionLevel.Optimal)gives you compression over buffering over a file, andCryptoStreamadds encryption the same way. InHttpClient, everyDelegatingHandleris 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
Decoratemethod. 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'sservices.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."
| Role | Example |
|---|---|
| Component (interface) | IProductRepository, Stream, HttpMessageHandler |
| Concrete component | SqlProductRepository, FileStream, SocketsHttpHandler |
| Decorator | CachedProductRepository, GZipStream, DelegatingHandler |
| 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 |
| 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 |
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.
Checks understanding of composition over inheritance and practical DI skills in .NET.
Green flags
Stream wrappers and DelegatingHandler.Decorate and shows a working registration.Red flags
Client βββΆ Β«interfaceΒ» IComponent
+ Operation()
β² β²
ConcreteComponent Decorator ββ inner: IComponent
Operation() { before(); inner.Operation(); after(); }
β² β²
LoggingDecorator CachingDecorator
Runtime chain: Logging βββΆ Caching βββΆ SqlRepository
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.
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.
DelegatingHandlerHttpClient 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.
Decorate worksIt 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.
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.
TimingRepository and CachedRepository decorators and register them both orders; log which runs first.DelegatingHandler that adds a correlation ID header and another that logs; check the order with AddHttpMessageHandler.GZipStream and try to decompress the file.IProductRepository and asserts the runtime type chain (outer decorator first).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
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.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.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.
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.
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.
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.
product:v1:{tenant}:{id}.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.
Last updated 18 Nov 2026.