Volume 6 · Chapter 6 — Enterprise Application Architecture and Design Patterns
Dependency Injection Architecture
6.1 Introduction
Dependency Injection (DI) is the technique of supplying a class’s collaborators from the outside rather than having it construct them. It is the practical mechanism behind the Dependency Inversion Principle and the glue that holds a Clean Architecture together: consumers depend on interfaces, and a container resolves the concrete implementations at runtime. Modern .NET ships with a capable DI container built in, so DI is the default idiom rather than an add-on.
6.2 Inversion of Control
Inversion of Control (IoC) is the broader idea that the flow of control - here, object creation and wiring - is handed to a framework instead of being written by hand in each class. DI is one form of IoC. The benefit is that a class stops being responsible for locating its dependencies and simply declares what it needs.
// Without DI: the class is welded to a concrete type and hard to test.
public class ReportService
{
private readonly SqlReportRepository _repo = new(); // tight coupling
}
// With DI: depends on an abstraction, supplied by the container.
public class ReportService
{
private readonly IReportRepository _repo;
public ReportService(IReportRepository repo) => _repo = repo;
}
6.3 The Built-in .NET Container
Registrations live in the composition root and map service types to implementations with a chosen lifetime. Constructor injection is the primary and recommended mechanism.
builder.Services.AddSingleton<IClock, SystemClock>();
builder.Services.AddScoped<IAccountRepository, EfAccountRepository>();
builder.Services.AddTransient<IEmailSender, SmtpEmailSender>();
6.4 Service Lifetimes
| Lifetime | Instances | Typical use |
|---|---|---|
| Singleton | One for the whole app | Stateless services, caches, configuration, clocks |
| Scoped | One per request/scope | DbContext, unit of work, per-request state |
| Transient | New every resolution | Lightweight, stateless helpers |
6.5 The Captive Dependency Trap
The most common DI bug in .NET is injecting a shorter-lived service (Scoped) into a longer-lived one (Singleton). The singleton captures the scoped instance and holds it forever, so a per-requestDbContextis shared across all requests - leading to threading errors and stale data. The diagram traces how the mistake plays out.
sequenceDiagram autonumber participant Root as Root Container (Singleton) participant Cache as CacheService (Singleton) participant Ctx as DbContext (Scoped) participant R1 as Request 1 participant R2 as Request 2 Root->>Cache: create once Cache->>Ctx: injected & captured (BUG) R1->>Cache: use Cache->>Ctx: query (scope of R1) R2->>Cache: use Cache->>Ctx: SAME captured context (wrong scope!) Note over Cache,Ctx: Scoped instance is now effectively a singleton
The fix is to inject anIServiceScopeFactory(or a factory delegate) into the singleton and create a fresh scope per unit of work, rather than capturing the scoped dependency directly.
public sealed class BackgroundProcessor : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
protected override async Task ExecuteAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
using var scope = _scopeFactory.CreateScope(); // fresh scope
var db = scope.ServiceProvider.GetRequiredService<BankingDbContext>();
await ProcessBatchAsync(db, ct);
}
}
}
6.6 Factory and Keyed Registrations
When the implementation depends on runtime data, register a factory or use .NET 8 keyed services to resolve by key. This keeps the selection logic in one place and avoids a service locator sprinkled through the code.
// .NET 8+ keyed services
builder.Services.AddKeyedScoped<IPaymentGateway, StripeGateway>("US");
builder.Services.AddKeyedScoped<IPaymentGateway, RazorpayGateway>("IN");
public class Checkout([FromKeyedServices("US")] IPaymentGateway gateway) { /* ... */ }
6.7 Decorator Registration
DI composes decorators cleanly: register the real service, then wrap it. Some teams use Scrutor to express this declaratively (services.Decorate<IProductQuery, CachingProductQuery>()), layering caching and logging without touching either the consumer or the implementation.
6.8 DI Anti-Patterns
- Service Locator- passing
IServiceProvideraround and resolving on demand hides dependencies and defeats the point of DI. - Over-injection- a constructor with ten dependencies signals a class doing too much (an SRP smell).
- Captive dependencies- scoped-into-singleton, as above.
- Interface for everything- abstractions with a single implementation and no seam add cost without benefit.
6.9 Organising Registrations at Scale
Large solutions group registrations by module using extension methods (services.AddPaymentsModule()), so each bounded context owns its wiring and the composition root stays readable. This also keeps module internals encapsulated.
What is the difference between Singleton, Scoped, and Transient?
They control instance lifetime. A Singleton is created once and shared for the application’s lifetime, so it must be thread-safe and stateless (or carefully synchronised). A Scoped instance lives for the duration of a scope - one per HTTP request in ASP.NET Core - which is whyDbContextis scoped. A Transient instance is created every time it is requested, suited to cheap, stateless helpers. The subtlety is composition: mixing lifetimes incorrectly (scoped into singleton) causes captive dependencies.
Why is the Service Locator considered an anti-pattern?
Because it hides a class’s true dependencies. With constructor injection, the signature declares everything the class needs, so it is honest and testable. A service locator (provider.GetService<T>()called inside methods) means dependencies are pulled from a global bag at runtime; you cannot tell what a class needs without reading its whole body, tests must configure a container, and failures surface at call time rather than construction time. It also couples code to the container itself. Occasionally it is unavoidable (in a factory or a framework extension point), but it should be the rare exception.
How do you consume a Scoped service inside a Singleton or a hosted background service?
You never inject the scoped service directly - that creates a captive dependency. Instead you injectIServiceScopeFactory, and for each unit of work callCreateScope(), resolve the scoped service from that scope, do the work, and dispose the scope. In aBackgroundServiceyou typically create a new scope per iteration or per message so each unit of work gets a freshDbContext. This mirrors how the framework creates a scope per HTTP request.
How do you unit test a class that uses DI?
Because dependencies are injected as interfaces, you construct the class in the test with test doubles - hand-written fakes or mocks (Moq, NSubstitute) - and assert on interactions or state. You do not need the DI container at all for unit tests; you just call the constructor. The container is exercised in integration tests, where you may replace specific registrations (for example, swap the real database for an in-memory or Testcontainers-backed one) usingWebApplicationFactoryandConfigureTestServices.
How do you design DI architecture for a large modular application?
I keep the composition root thin and push wiring into per-module registration extensions so each bounded context owns and encapsulates its services. I enforce that modules expose only their public contracts and register internals asinternaltypes, preventing cross-module reach-through. I standardise lifetime conventions (DbContext scoped, stateless services singleton) and add analyzers or startup validation (ValidateScopes,ValidateOnBuild) to catch captive dependencies at boot rather than in production. The aim is that adding a module is a one-line change to the root and that the wiring documents the architecture’s boundaries.
A constructor now takes twelve dependencies. What does that tell you and what do you do?
It is a design smell, not a DI problem. Twelve collaborators usually means the class violates SRP - it is orchestrating several responsibilities that should be separate. I’d look for clusters of dependencies that move together and extract them into cohesive collaborators (a facade or a domain service), or introduce a parameter object where several dependencies represent one concept. If the class is a handler doing genuine orchestration, some of those concerns (logging, validation, transactions) probably belong in a pipeline behaviour rather than injected directly. The fix is to reduce responsibilities, after which the dependency count falls out naturally.
6.10 Banking Enterprise Scenario
A bank’s platform registers each module - Accounts, Payments, Fraud, Notifications - through its ownAdd{Module}extension, with DbContexts scoped and stateless calculators as singletons. A fraud-scoring background worker processes a queue; because scoring needs a scopedDbContext, it creates a fresh scope per message viaIServiceScopeFactoryinstead of capturing one. Startup runs withValidateScopesenabled, so any accidental captive dependency fails the deployment rather than corrupting data in production.
Chapter Revision Notes
- DI supplies collaborators from outside; it implements DIP.
- Prefer constructor injection; avoid the service locator anti-pattern.
- Match lifetimes to state: singleton (stateless), scoped (per request), transient.
- Never capture a scoped service in a singleton - use a scope factory.
- Organise registrations per module; validate scopes at startup.