Architecting DI registrations in a modular monolith or large solution: one AddXModule extension per module, internal implementations behind public registration methods, TryAdd for shared infrastructure, explicit versus scanned registration (Scrutor) and its start-up and AOT cost, and testing the composition root with validation and architecture tests.
I make each module own its wiring: a public AddOrdersModule(this IServiceCollection, IConfiguration) extension next to internal implementations, so Program.cs becomes a short list of module calls that reads like the architecture. Shared infrastructure (clock, caching, messaging) is registered with TryAdd so modules don't depend on call order or duplicate it. For registration style, explicit registrations are clear, fast and Native AOT-safe; assembly scanning with Scrutor saves lines for dozens of handlers but costs start-up reflection, breaks trimming and can register things you didn't mean to, so I scope it to marker interfaces. Then I test the composition root: build the production host with ValidateOnBuild and ValidateScopes, resolve factory and open-generic services, and add architecture tests so modules can't reach into each other's internals.
"My starting rule is that each module owns its registrations. The Orders module exposes one public method,
AddOrdersModule(this IServiceCollection services, IConfiguration config), and everything it registers isinternal. Other modules can only depend on its public contracts.Program.csends up as ten lines ofAddXModulecalls plus shared infrastructure, and a new developer can see the shape of the system from it. Shared things likeTimeProvider,HybridCacheor the message bus are registered once withTryAddSingleton, either in anAddPlatform()call or defensively inside each module, so order doesn't matter and nothing is registered twice.For example, at [company] we [had a modular monolith with around 1,200 registrations, mostly in one 900-line
Program.cswith assembly scanning across every loaded assembly]. Start-up took [about 6 seconds], and scanning had picked up test doubles from a shared assembly in production. I [moved each module's wiring into its own extension method, limited scanning to marker interfaces in each module's assembly, and added a composition-root test with validation on]. [Start-up dropped to under 2 seconds and the test caught four lifetime bugs in the first week.]On scanning versus explicit: explicit registration is the default for anything with interesting lifetimes or decorators, because it's readable and works with Native AOT and trimming. Scanning earns its place for large uniform sets like 80 command handlers, scoped to a marker interface and one assembly. The mistake I see is scanning everything and treating the container as magic. The composition root is code too, so it gets tests: build the production host with validation on, resolve every endpoint's dependencies, and use architecture tests to stop modules referencing each other's internals."
| Approach | Good for | Weakness |
|---|---|---|
One big Program.cs |
Small apps | Unreadable past ~50 registrations; merge conflicts |
AddXModule() extension per module |
Modular monoliths, large solutions | Discipline to keep internals internal |
IModule interface discovered by reflection |
Plug-in systems | Hidden order and discovery; reflection at start-up |
| Scanning by convention (Scrutor) | Many uniform types (handlers, validators) | Start-up cost; trimming/AOT; accidental registrations |
| Source-generated registration | AOT, very large graphs | Tooling maturity; another dependency |
| Rule | Why |
|---|---|
TryAdd* for shared services |
Idempotent; no duplicates when two modules need the same thing |
TryAddEnumerable for multi-registrations (validators, hosted services) |
Avoids the same implementation twice in IEnumerable<T> |
Module options bound inside the module (AddOptions<OrdersOptions>().BindConfiguration("Orders")) |
Module owns its configuration section |
| No module resolves another module's internals | Keeps boundaries enforceable |
After splitting registrations per module and restricting scanning, a [modular monolith's] cold start in Azure Container Apps went from about 6 s to 1.8 s, merge conflicts in Program.cs disappeared, and the validation test found four captive dependencies and one duplicate hosted service that had been processing every message twice.
Checks whether the candidate can design DI wiring that reinforces module boundaries, scales to a large solution, and is tested.
Green flags
TryAdd/TryAddEnumerable for shared services and hosted servicesRed flags
The composition root is the one place where the object graph is assembled: Program.cs plus the extension methods it calls. Everything else receives dependencies through constructors.
Program.cs
AddPlatform() TimeProvider, HybridCache, bus, telemetry (TryAdd)
AddOrdersModule(cfg) internal handlers, repositories, options
AddBillingModule(cfg)
AddShippingModule(cfg)
...
Build() -> validated provider
A module assembly exposes contracts (IOrderQueries, integration events) and one public static class OrdersModule with AddOrdersModule. Implementations are internal sealed. The container can construct internal types because it uses reflection or compiled expressions, not normal C# visibility. Other modules physically can't reference the implementations, so boundaries are compiler-enforced.
TryAddSingleton<TService, TImpl>(): adds only if no registration for TService exists.TryAddEnumerable(ServiceDescriptor): adds only if that exact service/implementation pair isn't already present: right for IHostedService, validators, IConfigureOptions<T>.Replace / RemoveAll: for tests or deliberate overrides.Scrutor's Scan loads types from the assemblies you choose, filters them (AddClasses(c => c.AssignableTo<ICommandHandler>())) and registers each with a lifetime. Costs:
Start-up: Assembly.GetTypes() + filtering for every scanned assembly
Trimming: types found only by reflection may be trimmed -> IL2026/IL2072 warnings
Native AOT: reflection-based discovery is not supported reliably
Correctness: anything matching the filter is registered, including test doubles or obsolete types
Limit scanning to FromAssemblyOf<OrdersModuleMarker>() and a marker interface. For AOT, prefer explicit registration or a source generator that emits it.
WebApplicationFactory<Program> with UseEnvironment("Production"), ValidateOnBuild and ValidateScopes on.IHostedService implementation appears twice.AddFeatureModule extension and make its implementations internal.AddX twice and check whether hosted services or validators are duplicated; fix with TryAddEnumerable.builder.Build() with scanning across all loaded assemblies versus a single marker-scoped assembly.PublishTrimmed=true and read the warnings from reflection-based scanning.A module extension with internal implementations, idempotent shared infrastructure and scoped scanning (.NET 10, Scrutor):
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Shop.Orders;
public interface IOrderQueries { Task<OrderSummary?> GetAsync(Guid id, CancellationToken ct); }
public sealed record OrderSummary(Guid Id, decimal Total);
public interface ICommandHandler; // marker for scanning
public sealed class OrdersOptions { public int MaxLines { get; init; } = 100; }
internal sealed class OrderQueries(OrdersDbContext db) : IOrderQueries
{
public async Task<OrderSummary?> GetAsync(Guid id, CancellationToken ct) =>
await db.Orders.Where(o => o.Id == id)
.Select(o => new OrderSummary(o.Id, o.Total)).FirstOrDefaultAsync(ct);
}
public static class OrdersModule
{
public static IServiceCollection AddOrdersModule(this IServiceCollection services, IConfiguration config)
{
// Shared infrastructure: idempotent, order-independent.
services.TryAddSingleton(TimeProvider.System);
// Module-owned configuration section.
services.AddOptions<OrdersOptions>().BindConfiguration("Orders").ValidateOnStart();
services.AddDbContext<OrdersDbContext>(o =>
o.UseSqlServer(config.GetConnectionString("Orders")));
// Explicit for anything with interesting lifetimes.
services.AddScoped<IOrderQueries, OrderQueries>();
// Scanning only for a large uniform set, only in this assembly.
services.Scan(scan => scan
.FromAssemblyOf<ICommandHandler>()
.AddClasses(c => c.AssignableTo<ICommandHandler>(), publicOnly: false)
.AsSelfWithInterfaces()
.WithScopedLifetime());
// Hosted services: never twice, even if AddOrdersModule is called twice.
services.TryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, OrderOutboxRelay>());
return services;
}
}
// Program.cs: the composition root reads like the architecture.
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddPlatform(builder.Configuration)
.AddOrdersModule(builder.Configuration)
.AddBillingModule(builder.Configuration)
.AddShippingModule(builder.Configuration);
builder.Host.UseDefaultServiceProvider(o => { o.ValidateScopes = true; o.ValidateOnBuild = true; });
var app = builder.Build();
app.MapOrdersEndpoints();
app.Run();
Program.cs with hundreds of registrations. Why it is wrong: nobody can see module boundaries and every PR conflicts there. Instead: one AddXModule extension per module.internal.Add* for shared services in several modules. Why it is wrong: duplicates; the last one wins for single resolution and IEnumerable<T> gets both. Instead: TryAdd* and TryAddEnumerable.AddPlatform with TryAdd.The composition root is architecture you can execute. If Program.cs reads as a list of modules, each with a clear public contract and internal implementations, the DI setup is reinforcing the design; if it's a wall of scanning calls, it's hiding it. My defaults: explicit registration, module-owned extension methods, TryAdd for shared infrastructure, scanning only for large uniform sets, and a composition-root test as part of the definition of done.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Explicit per-module registration | Default for most solutions | More lines | Hundreds of uniform handlers |
| Marker-scoped scanning | Large uniform sets | Start-up reflection; trimming warnings | Native AOT, lifetimes that vary per type |
Reflection-discovered IModule |
True plug-ins loaded at run time | Hidden order, harder debugging | Modules known at compile time |
| Source-generated registration | AOT, start-up-critical services | Extra tooling | Small apps |
Measure start-up with a timer around builder.Build() and dotnet-trace on cold starts; measure boundary health with architecture-test failures per PR.
The composition root is the single place where the application's object graph is wired up: in ASP.NET Core, Program.cs and the AddXxx() extension methods it calls. It is the only code that knows about concrete implementations and the container.
Everything else asks for what it needs through its constructor. If business classes call IServiceProvider.GetService themselves, that is the service locator anti-pattern: their dependencies are hidden from the signature, a missing registration only shows up at run time, and unit tests need a container instead of a couple of fakes. Keeping resolution in the root keeps business code independent of the container, easier to test and easier to maintain. Framework-driven resolution (middleware Invoke parameters, [FromServices], Minimal API parameters) is fine because it is infrastructure acting on your behalf.
A library should plug into DI the way Microsoft's own packages do: a single AddMyLibrary(this IServiceCollection services, Action<MyLibraryOptions>? configure = null) extension method that registers everything and returns the collection or a builder for chained configuration.
Microsoft.Extensions.DependencyInjection.Abstractions and Options, never on a specific container.TryAdd for defaults the app can override and TryAddEnumerable for plug-ins, so calling it twice is harmless.ValidateOnStart.The trade-off: an AddX() method is convenient but hides registrations, so lifetimes and overrides must be documented and predictable.
The built-in container is deliberately a minimum: constructor injection, singleton/scoped/transient, open generics, IEnumerable<T> and, since .NET 8, keyed services. It leaves out property injection, assembly scanning, decorators, interception, child or tagged scopes and implicit Func<T>/Lazy<T>.
Scan() and Decorate() extension methods to IServiceCollection.UseServiceProviderFactory and add modules, decorators, interception and richer scopes.My default is built-in plus Scrutor if needed. The trade-off: a full container adds power but also a dependency, start-up cost and a learning curve for every new developer.
How to tell it (STAR)
**S:** [Our insurer's modular monolith] had about [1,200] registrations in one file, with scanning across every loaded assembly. **T:** Cold starts were [around 6 seconds], and we'd just found duplicate messages and a fake document signer running in production, so I was asked to sort out the wiring. **A:** A start-up trace showed most of the time in assembly scanning, and dumping the service collection showed [37] registrations nobody intended, including a duplicate hosted service. I moved each module's wiring into its own extension with internal implementations, limited scanning to marker interfaces, used `TryAdd` for shared services, and added composition-root and architecture tests. **R:** Cold start went to [1.8 seconds], duplicate publishing stopped, and the tests caught [four] lifetime bugs in the first week.
Last updated 23 Nov 2026.