Automatic dependency registration — scanning, Scrutor and source generators
Part 14 of 14 · ASP.NET Core from the ground upIn the DI post of this series, I argued for one registration extension per service: explicit, navigable with F12, testable. I still think that’s the right default. But I’ll admit the obvious downside, which one of the teams I worked with listed honestly in their own guideline: more extensions to write. In an API with two hundred handlers, that’s two hundred near-identical methods.
So sooner or later someone asks: can’t the container just find them? It can, in several ways. This post, the last one of the series, compares them.
The baseline: explicit extensions
Section titled “The baseline: explicit extensions”public static class AddPlaceOrderExtension{ public static IServiceCollection AddPlaceOrder(this IServiceCollection services) { services.AddOrderPricing(); services.TryAddScoped<PlaceOrderHandler>(); return services; }}Every alternative below should be measured against this: what do I gain in boilerplate, and what do I lose in visibility and safety?
Option 1: hand-written reflection scanning
Section titled “Option 1: hand-written reflection scanning”public static IServiceCollection AddHandlersFrom(this IServiceCollection services, Assembly assembly){ var handlerTypes = assembly.GetTypes() .Where(t => t is { IsClass: true, IsAbstract: false }) .SelectMany(t => t.GetInterfaces() .Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICommandHandler<,>)) .Select(i => (Service: i, Implementation: t)));
foreach (var (service, implementation) in handlerTypes) services.TryAddScoped(service, implementation);
return services;}It works, and every team that writes it eventually discovers the same edge cases: open generics, decorators that also implement the interface, test doubles in the same assembly, types that should be singletons. That’s why there’s a library for it.
Option 2: Scrutor
Section titled “Option 2: Scrutor”Scrutor adds a fluent scanning API on top of
IServiceCollection:
builder.Services.Scan(scan => scan .FromAssemblyOf<PlaceOrderHandler>() .AddClasses(classes => classes.AssignableTo(typeof(ICommandHandler<,>)), publicOnly: false) .AsImplementedInterfaces() .WithScopedLifetime() .AddClasses(classes => classes.InNamespaces("MyShop.Orders.Rules"), publicOnly: false) .UsingRegistrationStrategy(RegistrationStrategy.Skip) // like TryAdd .AsImplementedInterfaces() .WithSingletonLifetime());It also brings Decorate<TService, TDecorator>(), which the default container doesn’t have and
which is reason enough for many teams to add it.
Scanning by marker interface or base type (ICommandHandler<,>, IEndpoint) is the variant I’m
comfortable with. Scanning “every class in the assembly as its implemented interfaces” is the variant
that eventually registers something you didn’t want.
Option 3: walking the constructor graph
Section titled “Option 3: walking the constructor graph”A different idea, which one team I worked with designed for their backends: instead of scanning by convention, you name the root types you want, and the registration walks their constructors recursively and registers every concrete dependency it finds:
autoRegistration.RegisterWithDependencies<OrdersController>();The appeal is that it mirrors exactly what the app needs and nothing else. In practice you need rules for interfaces (which implementation?), lifetimes (singleton by default?) and settings (bind from configuration by type name?). Those rules end up being conventions again, just hidden in a different place. I haven’t seen this approach become mainstream, and I’d only consider it with a strong set of tests around it.
Option 4: source generators
Section titled “Option 4: source generators”The modern answer: let a source generator write the explicit registrations for you at compile time. You mark services with an attribute:
[RegisterScoped]internal sealed class PlaceOrderHandler(IOrderPricing pricing, IOrderRepository orders) : ICommandHandler<PlaceOrder, PlaceOrderResult>{ // ...}and the generator emits plain C# that you can read, debug and step into:
// <auto-generated/>public static partial class GeneratedRegistrations{ public static IServiceCollection AddMyShopOrders(this IServiceCollection services) { services.TryAddScoped<ICommandHandler<PlaceOrder, PlaceOrderResult>, PlaceOrderHandler>(); services.TryAddScoped<PlaceOrderHandler>(); // ... return services; }}Several open-source generators do exactly this (Injectio is one example), and writing your own incremental generator for a single marker interface is a manageable afternoon if you want full control. The important properties:
- No reflection at startup, so it works with trimming and Native AOT, where reflection scanning doesn’t.
- The result is visible. F12 on
AddMyShopOrdersshows the generated file. - Mistakes are compile-time errors, and a generator can even emit diagnostics, for example “singleton depends on a scoped service”.
Comparison
Section titled “Comparison”| Explicit extensions | Reflection / Scrutor | Graph walking | Source generator | |
|---|---|---|---|---|
| Boilerplate | High | Very low | Low | Low (one attribute) |
| See what’s registered | ✅ read the code | ❌ only at runtime | ❌ only at runtime | ✅ generated file |
| F12 dependency tree | ✅ | ❌ | ❌ | Partly |
| Startup cost | None | Assembly scan | Graph walk | None |
| Native AOT / trimming | ✅ | ❌ | ❌ | ✅ |
| Accidental registrations | ❌ | ⚠️ depends on filters | Rare | Only what’s marked |
| Lifetime per service explicit | ✅ | Per convention | Per convention | ✅ per attribute |
| Decorators | Manual | ✅ Scrutor Decorate |
❌ | Depends on generator |
What I actually do
Section titled “What I actually do”- Small to medium APIs: explicit extensions per feature. The boilerplate is real but small, and the readability pays for it.
- Many uniform types (handlers, endpoints, validators): scan by marker interface, either with Scrutor or a source generator. Everything else stays explicit. This is the sweet spot: you automate the repetitive, uniform part and keep the interesting registrations visible.
- AOT targets: source generator, no question.
What I avoid is the “scan everything” approach as the only registration mechanism. The feature
extensions from the DI post have a value beyond saving lines: they’re the place where a feature
declares what it needs. Automatic registration can fill a feature’s handlers in, but the feature
should still have its AddOrders().
public static IServiceCollection AddOrders(this IServiceCollection services, IConfiguration configuration){ services.AddCatalogClient(configuration); // explicit: external dependency with settings services.AddOptions<OrderOptions>() .BindConfiguration(OrderOptions.SectionName) .ValidateDataAnnotations() .ValidateOnStart();
services.Scan(scan => scan // automatic: the uniform part .FromAssemblyOf<OrderOptions>() .AddClasses(c => c.AssignableTo<IEndpoint>().InNamespaceOf<OrderOptions>(), publicOnly: false) .UsingRegistrationStrategy(RegistrationStrategy.Skip) .As<IEndpoint>() .WithSingletonLifetime());
return services;}Pitfalls
Section titled “Pitfalls”Lifetime by convention hides captive dependencies. “All handlers are singletons” is a convention
until one handler needs a DbContext. Keep ValidateScopes and ValidateOnBuild on outside
production; they work for scanned registrations too.
Test assemblies and fakes. Scanning FromApplicationDependencies() can pick up types from
assemblies you didn’t mean. Scan specific assemblies, ideally via a marker type.
Order-dependent registrations. Scanning has no meaningful order. If something depends on “last registration wins” (overriding a default), do that explicitly after the scan.
Startup time. Reflection scanning of large assemblies is measurable in serverless or scale-to-zero environments, where cold start matters. That’s one more argument for generators there.
“Where is this registered?” The question every new team member asks with scanning. Document the conventions in one place, next to the scan call, not in a wiki.
How to keep it safe
Section titled “How to keep it safe”- The resolve-everything test from the DI post: build the provider with
ValidateOnBuildand resolve every registered endpoint and handler. - A convention test: every class implementing
ICommandHandler<,>is registered exactly once. That catches the handler someone madeabstractby accident, or a double registration. - For generators: treat generator diagnostics as errors in the build.
Summary
Section titled “Summary”- Explicit per-feature extensions are the readable default; their cost is boilerplate.
- Reflection scanning and Scrutor remove boilerplate but make registrations invisible until runtime. Scan by marker interface, not “everything”.
- Graph walking is an interesting idea whose conventions end up hidden; use it with care.
- Source generators combine low boilerplate with visible, AOT-friendly code and compile-time checks.
- Mix them: automate the uniform part, keep features’ external dependencies and settings explicit, and keep the container validation tests on.