C# / .NET Compendium PLEN
.NET / C# / SOLID, Clean Code, DI

DI: service lifetimes and the most common pitfalls

The basics (what Singleton, Scoped and Transient are) are in the topic Singleton vs Transient vs Scoped. Here are the pitfalls that show up in real projects, with ready-made code examples.

The most important thing first: a lifetime does not decide which module gets which implementation. It decides how long an instance lives and who shares it. The IUnitOfWork trap (point 6) is a different matter: with several registrations of the same type, GetService<T> returns the last one. With Scoped or with Singleton the result would be the same: if several modules register their own IUnitOfWork, the Customers module may get IdentityDbContext, because it was registered last.

The three lifetimes

Lifetime Instance Typical use
Transient a new one every time it is resolved (every injection, every GetService) lightweight, stateless services
Scoped one per scope; in ASP.NET Core a scope = one HTTP request DbContext, Unit of Work, repositories, ICurrentUser
Singleton one for the whole container, lives until the application ends cache, configuration, clock; must be thread-safe

The rule: a dependency must live at least as long as the service that holds it. A singleton can depend only on singletons, a scoped service on scoped services and singletons, a transient on anything.

Pitfalls

1. Captive dependency

A singleton receives a scoped service in its constructor, so it holds it until the application ends. With a DbContext this means one context for all requests: a growing change tracker, stale data and exceptions on concurrent requests.

// BAD: singleton captures a scoped DbContext forever
services.AddSingleton<PriceCache>();
public sealed class PriceCache(CustomersDbContext dbContext) { }

A transient injected into a singleton also effectively becomes a singleton. Validation won't report this, so it is dangerous only when that transient holds state.

2. ValidateScopes / ValidateOnBuild

ValidateScopes throws an exception on a captive dependency and when a scoped service is resolved from the root provider. ValidateOnBuild checks at startup that every registration can be built. In Development both are enabled by default (WebApi and Worker through Host.CreateApplicationBuilder). It is worth enabling them always, because integration tests often don't run in Development:

builder.Host.UseDefaultServiceProvider(options =>
{
    options.ValidateScopes = true;
    options.ValidateOnBuild = true;
});

A limitation: validation won't look inside the factories sp => ....

3. DbContext is not thread-safe

AddDbContext registers it as scoped, that is one per request. Two concurrent operations on the same context end with the error "A second operation was started on this context":

// BAD: two concurrent operations on the same DbContext
await Task.WhenAll(
    dbContext.Customers.ToListAsync(cancellationToken),
    dbContext.Contacts.ToListAsync(cancellationToken));

For concurrency, or in a singleton, use AddDbContextFactory + IDbContextFactory<T> and create a separate context for each operation.

4. A transient IDisposable from the root provider

The container remembers every IDisposable object it created and disposes of it together with its scope. The root scope ends only with the application, so app.Services.GetService<SomeDisposableTransient>() in a loop causes a memory leak.

The other side of this rule: never call Dispose on an injected service, because the container owns it.

5. A BackgroundService in a Worker is a singleton

Don't inject a DbContext into it (point 1). Inject IServiceScopeFactory and create a scope for one unit of work:

public sealed class OutboxWorker(IServiceScopeFactory scopeFactory) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken cancellationToken)
    {
        while (!cancellationToken.IsCancellationRequested)
        {
            // One scope per iteration = fresh DbContext, disposed at the end
            await using var scope = scopeFactory.CreateAsyncScope();
            var dbContext = scope.ServiceProvider.GetRequiredService<CustomersDbContext>();
            // ... process batch ...
            await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);
        }
    }
}

The same applies to middleware with a conventional class (it is a singleton). Scoped services are then injected as a parameter of InvokeAsync, not into the constructor.

6. Multiple registrations of the same type (the IUnitOfWork trap)

  • GetRequiredService<IUnitOfWork>() returns the last registration and reports no error.
  • IEnumerable<IUnitOfWork> returns all of them, in registration order.
  • TryAddScoped adds a registration only if there isn't one yet. This is not a fix, because then the first one silently wins instead of the last.
  • TryAddEnumerable blocks a duplicate of the same interface + implementation pair. It is useful when registering e.g. several event handlers.

7. Forwarding: one instance under two types

This is a very real trap with a DbContext per module:

// BAD: builds a SECOND CustomersDbContext in the same scope.
// Repository adds to instance A, SaveChanges runs on instance B -> nothing saved.
services.AddScoped<ICustomersUnitOfWork, CustomersDbContext>();

// GOOD: forward to the instance registered by AddDbContext
services.AddScoped<ICustomersUnitOfWork>(sp => sp.GetRequiredService<CustomersDbContext>());

The same mechanism works with singletons. AddSingleton<IFoo, Foo>() and AddSingleton<IBar, Foo>() create two different Foo objects.

8. Keyed services (.NET 8+)

They let you register several implementations under keys:

services.AddKeyedScoped<IUnitOfWork>("customers",
    (sp, _) => sp.GetRequiredService<CustomersDbContext>());

public sealed class CreatePersonHandler([FromKeyedServices("customers")] IUnitOfWork unitOfWork) { }

It works, but the key is a string and a typo only shows up at runtime. A separate interface per module (ICustomersUnitOfWork) is checked by the compiler, which is an argument for that solution instead of keys.

Briefly, two other things

  • IOptions<T> is a singleton, IOptionsSnapshot<T> is scoped (you can't inject it into a singleton), and IOptionsMonitor<T> is a singleton with refreshing.
  • A typed HttpClient is transient, so don't hold it in a singleton.

Check questions

  1. ICurrentUser (reads the user from HttpContext) registered as a singleton. What will happen, and will ValidateScopes catch it?
  2. Two modules do TryAddScoped<IUnitOfWork, ...>. Which one wins, and why does the problem still exist?
  3. A repository gets CustomersDbContext, and a handler gets ICustomersUnitOfWork registered as AddScoped<ICustomersUnitOfWork, CustomersDbContext>(). What will you see in the database after SaveChangesAsync?
  4. A Worker processes 100 messages from a queue. How many scopes should it create, and why not one?
  5. Is a transient depending on a scoped service an error? And a scoped service depending on a transient?

See also

Buy me a coffee