📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

You are setting up DI for a large modular .NET 10 solution with ten feature modules and shared infrastructure. How do you organise the registrations? Discuss per-module extension methods, assembly scanning versus explicit registration, ordering and TryAdd for shared services, keeping implementations internal, start-up cost and Native AOT, and how you test the composition root.

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.

Senior Architecture Advanced architecture composition-root dependency-injection modular-monolith scrutor

🎯 Key points

  • One public AddXModule(IServiceCollection, IConfiguration) extension per module; implementations stay internal
  • Program.cs is a short list of module calls: the composition root reads like the architecture
  • TryAddSingleton<TimeProvider> for single shared services (first registration wins); TryAddEnumerable for multi-registrations such as IHostedService or validators (skips an identical service/implementation pair)
  • Explicit registration is the safe default: clear, fast and trimming/Native AOT-safe if you ever need it
  • Scanning (Scrutor) saves lines for large uniform sets but costs start-up reflection and accidental registrations; scope it to marker interfaces in one assembly
  • Unit-test each module's AddXModule against a fresh ServiceCollection (expected descriptors and lifetimes)
  • Integration-test the whole composition root: production environment with ValidateOnBuild/ValidateScopes, plus resolving factory and open-generic services
  • Architecture tests (NetArchTest, ArchUnitNET) stop modules reaching into each other's internals

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 is internal. Other modules can only depend on its public contracts. Program.cs ends up as ten lines of AddXModule calls plus shared infrastructure, and a new developer can see the shape of the system from it. Shared things like TimeProvider, HybridCache or the message bus are registered once with TryAddSingleton, either in an AddPlatform() 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.cs with 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."


Organising options

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

Shared infrastructure rules

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can design DI wiring that reinforces module boundaries, scales to a large solution, and is tested.

Green flags

  • One extension per module with internal implementations
  • TryAdd/TryAddEnumerable for shared services and hosted services
  • Clear trade-offs for scanning: start-up, trimming, AOT, accidental registrations
  • Tests the composition root and enforces boundaries with architecture tests

Red flags

  • Scans all assemblies by default
  • Public implementations everywhere
  • No idea how to test DI wiring

📚 Learn in depth

1. The composition root

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

2. Internal implementations, public registration

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.

3. TryAdd semantics

  • 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.

4. Scanning: how it works and what it costs

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.

5. Testing the composition root

  1. Validation test: WebApplicationFactory<Program> with UseEnvironment("Production"), ValidateOnBuild and ValidateScopes on.
  2. Resolve-all test: for factory registrations and closed open-generics that validation can't see, resolve them in a scope.
  3. Endpoint test: for each endpoint's handler or controller type, resolve its dependencies.
  4. Architecture tests: NetArchTest or ArchUnitNET rules such as "types in Billing must not depend on Orders.Internal".
  5. Duplicate-registration test: assert no IHostedService implementation appears twice.

Try it yourself

  1. Move one feature's registrations into an AddFeatureModule extension and make its implementations internal.
  2. Call a module's AddX twice and check whether hosted services or validators are duplicated; fix with TryAddEnumerable.
  3. Time builder.Build() with scanning across all loaded assemblies versus a single marker-scoped assembly.
  4. Publish with PublishTrimmed=true and read the warnings from reflection-based scanning.
  5. Write an ArchUnitNET rule that fails when one module references another's internal namespace.

💻 Code

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();

⚠ Common mistakes

  • Mistake: One 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.
  • Mistake: Making implementations public "so DI can find them". Why it is wrong: the container can build internal types, and public implementations let other modules bypass contracts. Instead: keep implementations internal.
  • Mistake: Scanning every loaded assembly. Why it is wrong: slow start-up, accidental registrations (test doubles, obsolete types) and broken trimming. Instead: scan one assembly with a marker interface, or register explicitly.
  • Mistake: Using 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.
  • Mistake: Hidden order dependencies between modules ("Billing must be added after Orders"). Why it is wrong: fragile and undocumented. Instead: make modules independent; put shared registrations in AddPlatform with TryAdd.
  • Mistake: No tests for the composition root. Why it is wrong: wiring errors only show up at run time, often in rarely used paths. Instead: a validation test in the production environment plus architecture tests.
  • Mistake: Choosing reflection-based scanning in a service that targets Native AOT. Why it is wrong: discovery is unreliable and produces trimming warnings. Instead: explicit or source-generated registration.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the composition root Why: Checks the definition of the composition root and why only it should resolve services
    How to answer

    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.

  2. When: Candidate mentions AddXModule extension methods or TryAdd Why: Checks DI design for reusable libraries
    How to answer

    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.

    • Depend on Microsoft.Extensions.DependencyInjection.Abstractions and Options, never on a specific container.
    • Use TryAdd for defaults the app can override and TryAddEnumerable for plug-ins, so calling it twice is harmless.
    • Configure through the options pattern with validation and ValidateOnStart.

    The trade-off: an AddX() method is convenient but hides registrations, so lifetimes and overrides must be documented and predictable.

  3. When: Candidate mentions Scrutor or another container Why: Checks when the built-in container is enough and what third-party tools add
    How to answer

    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>.

    • Scrutor isn't a container; it adds Scan() and Decorate() extension methods to IServiceCollection.
    • Autofac and Lamar replace the provider through 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.

🛠 Real-world problems: how you handle them

Unscoped assembly scanning slowed start-up and registered test doubles
Situation
A [modular monolith for an insurer] on .NET [10] with about [1,200] registrations, deployed to Azure Container Apps [Australia East]. Registrations lived in one [900]-line `Program.cs` that used Scrutor to scan all loaded assemblies for anything ending in `Service`.
Signals
Cold start took about [6] seconds, so scale-out during peak lagged and some requests timed out. In production, a `FakeDocumentSigner` from a shared testing-utilities assembly was resolved in one code path, and a hosted outbox relay was registered twice, publishing every message twice.
Investigation
Used `dotnet-trace` on a cold start and saw most time in `Assembly.GetTypes` and type filtering. Dumped the `IServiceCollection` in a test to a CSV (service, implementation, lifetime) and found [37] unexpected registrations, two `OrderOutboxRelay` hosted services and the fake signer.
Resolution
Immediate: removed the testing-utilities reference from the production project and deduplicated the hosted service. Then moved each module's wiring into an `AddXModule` extension with internal implementations, limited scanning to marker interfaces per assembly, and switched shared registrations to `TryAdd`/`TryAddEnumerable`.
Prevention
A composition-root test in the Production environment with validation on; a test asserting no duplicate `IHostedService` implementations; ArchUnitNET rules between modules; a snapshot test of the registration list reviewed in PRs.

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.

↩ Usually asked after

More in Advanced DI

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me