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

LifetimeOne instance perTypical use
Transienteach time it is requestedsmall stateless services
Scopedscope (in a web app, one HTTP request)DbContext, unit-of-work, per-request state
Singletonapplicationcaches, 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

Design habits

  1. Prefer constructor injection. Avoid injecting IServiceProvider into business classes.
  2. Keep constructors cheap and free of side effects, because the container calls them whenever it needs an instance.
  3. Many parameters in a constructor is a hint that a class has too many responsibilities, not a problem for the container.
  4. Register against interfaces you own at module boundaries, but do not create an interface for every class.
  5. 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

Practise this topic: C# & .NET C# & .NET › Design Principles & Patterns

More guides