skip to content

With Scrutor, how does services.Decorate(typeof(IQueryHandler<,>), typeof(CachingQueryHandler<,>)) wrap forty scanned handlers, and what makes it throw or skip registrations?

level: seniorimportance: should knowfreq 33%

answer

  1. Decorate rewrites existing descriptors
  2. original kept as a keyed service
  3. decorator inherits the lifetime
  4. DecorationException versus TryDecorate's bool
  5. open generic registrations are not decorated

basics

~20 s

Decorate walks the descriptors registered so far, re-registers each matching handler under a generated key and replaces it with a factory that builds CachingQueryHandler around it, keeping its lifetime. It throws DecorationException when nothing matches; open generic registrations are skipped.

solid answer

~50 s

`Decorate` changes registrations that **already exist**, so it must run after the `Scan` that added the handlers. For every descriptor whose service type is a closed `IQueryHandler<TQuery, TResult>`, Scrutor 7 re-adds the original as a **keyed** service (key built from the type name, a GUID and the suffix `+Decorated`) and replaces the original slot with a factory of the **same lifetime**. That factory resolves the keyed original and calls `ActivatorUtilities.CreateInstance` for `CachingQueryHandler<TQuery, TResult>`, so the decorator's other constructor parameters, such as a cache service, come from the container. A second `Decorate` call wraps the result again and becomes the outermost layer. If no descriptor matched, `Decorate` throws `DecorationException` ("Could not find any registered services for type ..."), while `TryDecorate` returns `false`. Open generic registrations such as `AddScoped(typeof(IQueryHandler<,>), typeof(...))` are skipped, as are closed types whose arguments break the decorator's generic constraints.

code

csharp · 11 lines
csharp
public sealed class CachingQueryHandler<TQuery, TResult>(
    IQueryHandler<TQuery, TResult> inner,
    HybridCache cache) : IQueryHandler<TQuery, TResult>
    where TQuery : ICacheableQuery
{
    public async Task<TResult> HandleAsync(TQuery query, CancellationToken ct) =>
        await cache.GetOrCreateAsync(
            query.CacheKey,
            async token => await inner.HandleAsync(query, token),
            cancellationToken: ct);
}

go deeper

for a junior

Recall that Decorate wraps an existing registration and must run after the services it decorates are registered.

for a middle

Explain how Scrutor keeps the original as a keyed service, why the decorator shares its lifetime, and what DecorationException and TryDecorate signal.

for a senior

Reason about open generic matching, constraint-based skipping, stacking order as behaviour, and the hidden keyed twins when diagnosing a decorator that did not apply.

for a principal

Choose between container decorators, MediatR behaviors and endpoint filters for cross-cutting concerns, weighing discoverability, ordering control and testability.

## The goal In the logistics platform, forty query handlers were registered by `Scan`. Many queries, such as depot lists and tariff tables, change rarely, so the team wants a `CachingQueryHandler<TQuery, TResult>` that checks a cache before calling the real handler, without editing forty classes. The built-in container has no decoration feature; Scrutor's `Decorate` adds one by rewriting the service collection. (The Decorator pattern itself is the general idea; this answer is about what Scrutor does to the registrations.) ```csharp builder.Services.Scan(s => s .FromAssemblyOf<GetShipmentHandler>() .AddClasses(c => c.AssignableTo(typeof(IQueryHandler<,>))) .AsImplementedInterfaces() .WithScopedLifetime()); builder.Services.Decorate(typeof(IQueryHandler<,>), typeof(CachingQueryHandler<,>)); ``` ## What Decorate does to each descriptor Scrutor 7 walks the collection **as it is at that moment**. For each descriptor that matches: 1. It adds a copy of the original registration under a generated **service key** (the service type name, a GUID and `+Decorated`), using the keyed-services support that `Microsoft.Extensions.DependencyInjection` has had since .NET 8. 2. It **replaces the original descriptor in place** with a factory registration that keeps the original **lifetime**. 3. When resolved, that factory calls `GetRequiredKeyedService` for the original and builds the decorator with `ActivatorUtilities.CreateInstance(provider, decoratorType, original)`. The decorator's constructor receives the inner handler plus anything else it asks for from the container. Consumers still ask for `IQueryHandler<ListDepots, IReadOnlyList<DepotDto>>` and now receive a `CachingQueryHandler<ListDepots, IReadOnlyList<DepotDto>>` wrapping `ListDepotsHandler`. Because the factory keeps the handler's lifetime, a scoped handler gets a scoped decorator. ## Matching rules for open generics | Registration in the collection | Decorated by `Decorate(typeof(IQueryHandler<,>), typeof(CachingQueryHandler<,>))`? | |---|---| | Closed `IQueryHandler<GetShipment, ShipmentDto>` from `Scan` | yes | | Open `AddScoped(typeof(IQueryHandler<,>), typeof(GenericQueryHandler<,>))` | no, open generic registrations are skipped | | Closed type whose arguments break `CachingQueryHandler`'s constraints | no, skipped | | Registration added **after** the `Decorate` call | no, it did not exist yet | If the decorator declares `where TResult : class`, handlers returning a value type are left undecorated rather than failing. That is useful, but it also means a constraint can silently exclude handlers you expected to be cached. ## Throw or skip - `Decorate` throws **`DecorationException`**, an `InvalidOperationException`, with the message "Could not find any registered services for type ...", when not a single descriptor matched. The usual cause is ordering: `Decorate` called before `Scan`, or the handlers registered only as an open generic. - `TryDecorate` has the same signatures but returns `bool` instead of throwing, for optional decoration. - The `Decorate(Type, Type)` overloads match **unkeyed** descriptors only, so a handler you registered with `AddKeyedScoped` is not wrapped by them. ## Stacking decorators Each call wraps whatever is registered now: ```csharp services.Decorate(typeof(IQueryHandler<,>), typeof(CachingQueryHandler<,>)); services.Decorate(typeof(IQueryHandler<,>), typeof(TimingQueryHandler<,>)); // resolve: TimingQueryHandler -> CachingQueryHandler -> ListDepotsHandler ``` The **last** `Decorate` is the **outermost** layer. Order is behaviour: timing outside caching measures cache hits too, while timing inside caching measures only real executions. ## Production cautions - Every decorated handler now has a hidden keyed twin; tools or tests that count descriptors see twice as many. - The decorator's dependencies must be resolvable at the handler's lifetime; a scoped decorator depending on a scoped cache-key builder is fine, a singleton handler decorated with something that needs a scoped service is not. - When the pipeline needs more than two or three layers, MediatR pipeline behaviors or endpoint filters are often clearer than stacked container decorators.

  • Why does Decorate throw DecorationException when the handlers were registered as AddScoped(typeof(IQueryHandler<,>), typeof(GenericQueryHandler<,>))?
    Scrutor's open generic decoration matches only **closed** registrations of the generic interface, such as those `Scan` produces with `AsImplementedInterfaces()`. An open generic registration has no concrete type arguments to close the decorator over, so it is skipped, nothing matches, and `Decorate` throws. Register the handlers as closed types, or decorate inside the generic implementation.
  • How do you verify the decoration order in a test?
    Build the same service collection, create a scope, resolve one closed handler such as `IQueryHandler<ListDepots, IReadOnlyList<DepotDto>>`, and assert the runtime type of the outer instance, then of its inner field if exposed. The last `Decorate` call should be the outermost type.

  • Decorate can be called before Scan; it applies to handlers registered later.
  • Decorate always registers the decorator as a singleton.
  • The first Decorate call becomes the outermost wrapper.
  • TryDecorate throws DecorationException when no registration matches.
  • An open generic AddScoped(typeof(IQueryHandler<,>), ...) registration is decorated like a scanned one.