skip to content

With Scrutor 7 in ASP.NET Core, which Scan defaults surprise teams (lifetime, visibility, duplicates and interfaces), and how do you override each?

level: middleimportance: should knowfreq 28%

answer

  1. no lifetime call means transient
  2. AddClasses(publicOnly: false)
  3. RegistrationStrategy.Append by default
  4. UsingRegistrationStrategy(Skip / Throw / Replace())
  5. IDisposable counts as an interface

basics

~10 s

Without a lifetime call Scrutor registers transient; AddClasses() skips internal classes; the default RegistrationStrategy.Append duplicates anything already registered; and AsImplementedInterfaces registers every interface, IDisposable included. Override with With*Lifetime, publicOnly: false, UsingRegistrationStrategy and a predicate.

solid answer

~40 s

Four defaults catch teams out. **Lifetime**: omit `WithScopedLifetime()` and every scanned registration is **transient**. **Visibility**: `AddClasses()` takes only public, non-abstract, non-compiler-generated classes, so `internal sealed` handlers are silently skipped; use the `publicOnly: false` overloads. **Duplicates**: the default strategy is `RegistrationStrategy.Append`, so a handler registered by hand and again by `Scan` ends up twice. Choose `UsingRegistrationStrategy(RegistrationStrategy.Skip)` (a `TryAdd` per descriptor), `RegistrationStrategy.Throw` (throws `DuplicateTypeRegistrationException`) or `RegistrationStrategy.Replace()`. **Interfaces**: for a non-generic class, `AsImplementedInterfaces()` filters out only `IEnumerable` and `IEnumerable<T>`, so a handler that implements `IDisposable` is also registered as `IDisposable`; pass a predicate or use `AsMatchingInterface()`. Also, `AsImplementedInterfaces` gives each interface its own descriptor, so a scoped class behind two interfaces yields two instances per request; `AsSelfWithInterfaces()` shares one.

code

csharp · 9 lines
csharp
using Scrutor; // RegistrationStrategy lives here; Scan itself is in Microsoft.Extensions.DependencyInjection

builder.Services.Scan(scan => scan
    .FromAssemblyOf<GetShipmentHandler>()
    .AddClasses(c => c.AssignableTo(typeof(IQueryHandler<,>)), publicOnly: false)
    .UsingRegistrationStrategy(RegistrationStrategy.Throw)
    .AsImplementedInterfaces(i => i.IsGenericType
        && i.GetGenericTypeDefinition() == typeof(IQueryHandler<,>))
    .WithScopedLifetime());

go deeper

for a junior

Recall that an omitted lifetime means transient and that AddClasses() takes public classes only.

for a middle

Explain the four registration strategies, when Skip or Throw is the right default, and how AsImplementedInterfaces differs from AsSelfWithInterfaces in instance sharing.

for a senior

Diagnose the production symptoms each default causes, such as missing internal handlers, double execution or unexpected IDisposable registrations, and set team-wide conventions that make them explicit.

for a principal

Weigh convention-based registration against explicit lists for a growing platform, including how reviews and tests keep scanned registrations predictable.

## Defaults are where scanning goes wrong `Scan` writes many registrations from one statement, so a default you did not think about is applied forty times. In the logistics platform the forty query handlers were scanned without much thought, and the four defaults below each caused a separate incident. ## 1. Lifetime: transient unless you say otherwise Each `AddClasses(...)` block takes the lifetime from its `WithScopedLifetime()`, `WithSingletonLifetime()`, `WithTransientLifetime()` or `WithLifetime(...)` call. With none, Scrutor falls back to `ServiceLifetime.Transient`. That is rarely a correctness bug, but a handler that holds expensive state, or one the team assumed was shared within a request, behaves differently from what the code review expected. ## 2. Visibility: internal classes are skipped `AddClasses()` and `AddClasses(filter)` take **public**, non-abstract classes only, and exclude compiler-generated types. Handlers declared `internal sealed class GetShipmentHandler`, a common style in feature folders, are silently left out, and the first request that needs one fails. The fix is explicit: ```csharp .AddClasses(c => c.AssignableTo(typeof(IQueryHandler<,>)), publicOnly: false) ``` ## 3. Duplicates: Append is the default strategy Scrutor applies each descriptor through a `RegistrationStrategy`, and the default is **`Append`**: a plain `services.Add`. If `ListDepotsHandler` was already registered by hand, the scan adds a second descriptor. A single resolve still gets one (the last), but `IEnumerable<T>` consumers see both, and a later decoration wraps both. | Strategy | Behaviour per scanned descriptor | |---|---| | `RegistrationStrategy.Append` (default) | always adds | | `RegistrationStrategy.Skip` | `TryAdd`: adds only if the service type is not registered yet | | `RegistrationStrategy.Throw` | throws `DuplicateTypeRegistrationException` if the service type is registered | | `RegistrationStrategy.Replace()` | removes **all** existing descriptors of that service type, then adds | Set it per selection with `UsingRegistrationStrategy(...)` right after `AddClasses(...)`. Note that `Skip` checks the service type only: for an interface that is meant to have several implementations, it keeps the first one and drops the rest. `Replace()` defaults to `ReplacementBehavior.ServiceType`; `Replace(ReplacementBehavior.ImplementationType)` removes by implementation type instead, and `ReplacementBehavior.All` does both. ## 4. Interfaces: AsImplementedInterfaces takes them all For a non-generic class, `AsImplementedInterfaces()` registers every interface it implements except `IEnumerable` and `IEnumerable<T>` (for an open generic class it also drops interfaces whose generic arity does not match). A handler that implements `IDisposable`, `IAsyncDisposable` or a marker interface is registered under those too. A consumer that injects `IEnumerable<IDisposable>` would then receive the handler, which is almost never intended. Three ways to narrow it: - a predicate: `AsImplementedInterfaces(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IQueryHandler<,>))`; - `AsMatchingInterface()`, which registers only the interface named `I` + class name; - `As(typeof(...))` or `As<T>()` for a single, explicit service type. ## A side effect of one descriptor per interface `AsImplementedInterfaces()` creates a **separate descriptor** for each interface, each with the class as its implementation. Under a scoped lifetime, a class that implements both `IQueryHandler<TrackParcel, ParcelStatus>` and `IParcelCacheWarmer` therefore produces **two instances** per request, one per interface. If the instance must be shared, use `AsSelfWithInterfaces()`: it registers the class itself and forwards each interface to that registration, so all of them resolve the same object within the lifetime. ## Checklist for a scan 1. State the lifetime on every `AddClasses` block. 2. Decide whether internal types belong in, and pass `publicOnly: false` if so. 3. Pick a registration strategy when manual registrations of the same types exist. 4. Restrict the interfaces with a predicate, `AsMatchingInterface()` or `As<T>()`. 5. Back it with a test that resolves every expected handler.

  • Why can RegistrationStrategy.Skip drop implementations you wanted?
    `Skip` applies each descriptor with `TryAdd`, which checks only whether the service type is already registered. That is right for one handler per closed `IQueryHandler<TQuery, TResult>`, but for an interface meant to have several implementations, such as `IShipmentEventSink`, only the first scanned or hand-registered implementation survives and the rest are silently skipped.
  • How do Scrutor's RegistrationStrategy.Replace() and the built-in IServiceCollection.Replace differ?
    Scrutor's `Replace()` strategy, with its default `ReplacementBehavior.ServiceType`, removes every existing descriptor of the scanned service type before adding the new one. The built-in `Replace` extension removes only the first matching descriptor. After a Scrutor replace there is exactly one registration of that service type; after the built-in one, earlier duplicates can survive.

  • Scrutor registers scanned classes as scoped when no lifetime is given.
  • AddClasses() includes internal classes as long as they implement the interface.
  • Scan skips any service type that was already registered by hand.
  • AsImplementedInterfaces() never registers framework interfaces like IDisposable.
  • A scoped class behind two interfaces is one instance per request with AsImplementedInterfaces().