CS Fundamentals Trainer · Guides
Dependency injection in .NET: lifetimes, captive dependencies and scopes
What the built-in container does, the three lifetimes (transient, scoped, singleton) and when each is right, the captive-dependency bug where a long-lived service holds a short-lived one, how scopes map to requests, injecting factories and IOptions, and how to test with it.
3 min read
ASP.NET Core and the generic host include a dependency injection (DI) container. You register services with a lifetime, ask for them in constructors, and the container builds the object graph. Most of the trouble comes from choosing the wrong lifetime or mixing lifetimes.
Registration and use
builder.Services.AddTransient<IClock, SystemClock>();
builder.Services.AddScoped<IOrderRepository, OrderRepository>();
builder.Services.AddSingleton<ICatalogCache, CatalogCache>();
public class OrderService(IOrderRepository orders, IClock clock) { /* primary constructor */ }
A class declares what it needs in its constructor; it does not create or look up anything itself. That makes dependencies visible and lets tests substitute fakes.
The three lifetimes
| Lifetime | One instance per | Typical use |
|---|---|---|
| Transient | each time it is requested | small stateless services |
| Scoped | scope (in a web app, one HTTP request) | DbContext, unit-of-work, per-request state |
| Singleton | application | caches, configuration, HttpClient factories, expensive thread-safe objects |
Singleton services must be thread-safe, because every request uses the same instance at the same time. Scoped services are not shared between requests, so they can hold request state.
The captive dependency
A service must never depend on one with a shorter lifetime. If a singleton takes a scoped service in its constructor, the container gives it one instance and the singleton keeps it forever, so a "per-request" DbContext becomes a process-wide one, shared across threads (it is not thread-safe) and long after its request ended. This is called a captive dependency.
builder.Services.AddSingleton<ReportCache>(); // takes IOrderRepository (scoped) in its constructor: bug
ASP.NET Core validates this at startup in the Development environment (ValidateScopes/ValidateOnBuild). Turn the same validation on elsewhere in tests. Fixes: make the consumer scoped; or make the singleton create a scope when it needs the scoped service:
public class ReportCache(IServiceScopeFactory scopes)
{
public async Task RefreshAsync()
{
using var scope = scopes.CreateScope();
var repo = scope.ServiceProvider.GetRequiredService<IOrderRepository>();
// use repo, then the scope (and its scoped services) is disposed
}
}
Background services (BackgroundService) are singletons, so this pattern is the normal way for them to use a DbContext.
Disposal
The container disposes the IDisposable services it created, when their scope ends (the app, for singletons). Services you create with new and register as an instance (AddSingleton(instance)) are not disposed by it. Transient disposables resolved from the root provider live until the app ends, which is a slow memory leak in long-running processes; resolve them in a scope.
Factories and options
- When a class needs several instances, or needs one later, inject a factory:
Func<IThing>(if registered),IServiceProvider(a last resort, because it hides dependencies, often called the service locator pattern) or a domain-specific factory interface. IHttpClientFactorymanagesHttpClienthandler lifetime and pooling; do not create a newHttpClientfor every call, nor keep a single static one forever in an app whose DNS changes.- Configuration goes through
IOptions<T>(a snapshot),IOptionsSnapshot<T>(per request) orIOptionsMonitor<T>(live changes). - Keyed services (.NET 8) let you register several implementations of one interface under a key and request one with
[FromKeyedServices("name")].
Design habits
- Prefer constructor injection. Avoid injecting
IServiceProviderinto business classes. - Keep constructors cheap and free of side effects, because the container calls them whenever it needs an instance.
- Many parameters in a constructor is a hint that a class has too many responsibilities, not a problem for the container.
- Register against interfaces you own at module boundaries, but do not create an interface for every class.
- Avoid static access to services; it defeats the purpose.
Testing
Unit tests need no container: construct the class with fakes. For integration tests, WebApplicationFactory<T> starts the real app in memory, and ConfigureTestServices lets you replace a registration (for example the clock or an email sender) with a fake.
Sources
- Microsoft Learn: Dependency injection in .NET.
- Microsoft Learn: Dependency injection guidelines.
- Microsoft Learn: Integration tests in ASP.NET Core.
Practise this topic: C# & .NET C# & .NET › Design Principles & Patterns