skip to content

With Scrutor in ASP.NET Core, what does each step of services.Scan(s => s.FromAssemblyOf<GetShipmentHandler>().AddClasses(...).AsImplementedInterfaces().WithScopedLifetime()) do?

level: juniorimportance: should knowfreq 36%

answer

  1. the built-in container cannot scan
  2. a marker type picks the assembly
  3. public, non-abstract classes, then a filter
  4. one descriptor per implemented interface
  5. lifetime set last in the chain

basics

~10 s

Scan reflects over the assembly containing GetShipmentHandler, AddClasses picks its public non-abstract classes (optionally filtered), AsImplementedInterfaces registers each class under every interface it implements, and WithScopedLifetime makes those registrations scoped.

solid answer

~40 s

The built-in container has no assembly scanning, so the **Scrutor** package adds a `Scan` extension method on `IServiceCollection`. Read the chain left to right. `FromAssemblyOf<GetShipmentHandler>()` uses the type only as a marker: it selects the assembly that contains it. `AddClasses(c => c.AssignableTo(typeof(IQueryHandler<,>)))` takes that assembly's public, non-abstract classes and keeps those that implement the open generic interface. `AsImplementedInterfaces()` says what to register them as: one `ServiceDescriptor` per interface each class implements, for example the closed `IQueryHandler<GetShipment, ShipmentDto>`. `WithScopedLifetime()` sets the lifetime. The result is the same list of descriptors that forty hand-written `AddScoped` lines would produce, created once by reflection at startup.

code

xml · 3 lines
xml
<ItemGroup>
  <PackageReference Include="Scrutor" Version="7.0.0" />
</ItemGroup>

go deeper

for a junior

Recall what each link does: assembly by marker type, which classes, registered as what, with which lifetime. Know that Scrutor is a separate package.

for a middle

Explain that Scan only produces ordinary descriptors for the built-in container, and choose between AsImplementedInterfaces, AsMatchingInterface and AsSelfWithInterfaces.

for a senior

Discuss what convention-based registration hides, how to keep filters narrow, and how a test that resolves every handler restores the safety of explicit wiring.

for a principal

Decide where conventions are worth their opacity in a large codebase and how teams document and enforce the conventions scanning relies on.

## Why the package exists ASP.NET Core's built-in container (`Microsoft.Extensions.DependencyInjection`) only knows the registrations you add one by one. **Scrutor** is a NuGet package that adds two extension methods to `IServiceCollection`: `Scan`, for registering types by convention, and `Decorate`, for wrapping registered services. Both put ordinary `ServiceDescriptor`s into the same collection, so the built-in container still does the resolving. Picture a logistics platform with forty query handlers such as `GetShipmentHandler`, `ListDepotsHandler` and `TrackParcelHandler`, each implementing `IQueryHandler<TQuery, TResult>`. Without scanning, every new handler needs another registration line, and a forgotten one surfaces as a resolve error at run time. ## The chain, step by step ```csharp builder.Services.Scan(scan => scan .FromAssemblyOf<GetShipmentHandler>() .AddClasses(c => c.AssignableTo(typeof(IQueryHandler<,>))) .AsImplementedInterfaces() .WithScopedLifetime()); ``` 1. **`Scan(...)`** opens the fluent selector. The `Scan` method lives in the `Microsoft.Extensions.DependencyInjection` namespace, so no extra `using` is needed once the package is referenced. 2. **`FromAssemblyOf<GetShipmentHandler>()`** chooses **where** to look: the assembly that contains `GetShipmentHandler`. The type is only a marker. Siblings include `FromAssembliesOf(...)`, `FromAssemblies(...)` and `FromEntryAssembly()`. 3. **`AddClasses(...)`** chooses **which** types: by default, the public, non-abstract classes of that assembly, filtered by the lambda. `AssignableTo(typeof(IQueryHandler<,>))` accepts an open generic and keeps every class that implements any closed form of it. Other filters include `InNamespaceOf<T>()`, `WithAttribute<T>()` and `Where(...)`. 4. **`AsImplementedInterfaces()`** chooses **what to register them as**: one descriptor per interface each class implements. `GetShipmentHandler : IQueryHandler<GetShipment, ShipmentDto>` becomes a registration of `IQueryHandler<GetShipment, ShipmentDto>` with implementation `GetShipmentHandler`. 5. **`WithScopedLifetime()`** chooses **how long** instances live. `WithTransientLifetime()` and `WithSingletonLifetime()` are the alternatives. ## What ends up in the collection | Class | Registered service type | Lifetime | |---|---|---| | `GetShipmentHandler` | `IQueryHandler<GetShipment, ShipmentDto>` | scoped | | `ListDepotsHandler` | `IQueryHandler<ListDepots, IReadOnlyList<DepotDto>>` | scoped | | `TrackParcelHandler` | `IQueryHandler<TrackParcel, ParcelStatus>` | scoped | A dispatcher or endpoint then asks for `IQueryHandler<GetShipment, ShipmentDto>` exactly as if it had been registered by hand. You can chain several `AddClasses(...)` blocks in one `Scan` call, each with its own `As...` and lifetime, for example validators as transient and repositories as scoped. ## Choosing the "as" step | Method | Registers each class as | |---|---| | `AsImplementedInterfaces()` | every interface it implements, one descriptor each | | `AsMatchingInterface()` | only the interface named `I` + class name, such as `IShipmentClock` for `ShipmentClock` | | `AsSelf()` | the concrete class itself | | `AsSelfWithInterfaces()` | the class, plus each interface forwarded to that same registration | | `As<T>()` | one service type you name | ## What it costs - Scanning runs **reflection over the assembly once**, when `Scan` executes during startup; after that, resolving costs the same as a hand-written registration. - The registration list is no longer visible in `Program.cs`. When a handler is not found, inspect `builder.Services` or write a test that resolves every handler type. - A broad filter registers more than you meant. A class that also implements another interface gets a registration for that one too, which is why narrow filters and the right "as" method matter.

  • How would you register validators as transient and query handlers as scoped in one Scan call?
    Chain two selections after the assembly: `.AddClasses(c => c.AssignableTo(typeof(IValidator<>))).AsImplementedInterfaces().WithTransientLifetime()` followed by `.AddClasses(c => c.AssignableTo(typeof(IQueryHandler<,>))).AsImplementedInterfaces().WithScopedLifetime()`. Each `AddClasses` starts again from the full set of classes in the selected assemblies, with its own filter, service types and lifetime.
  • Does scanning slow down every request?
    No. `Scan` runs once while the service collection is being built, reflects over the selected assemblies and adds ordinary descriptors. From then on the built-in container resolves them exactly like hand-written registrations, so the cost is paid at startup only.

  • FromAssemblyOf<GetShipmentHandler>() registers only GetShipmentHandler itself.
  • Scrutor replaces the built-in container with its own resolver.
  • Scan runs reflection again on every request to find handlers.
  • AsImplementedInterfaces() registers each class under its own concrete type.
  • AddClasses() picks up abstract base classes along with concrete handlers.