When we register a service with dependency injection, we also decide how long its instances should live: when they are created, which consumers share them, and when their resources are released.

An unsuitable lifetime can cause request-specific information to survive into later requests, expose an object to unsafe concurrent access, or retain resources longer than intended. Choosing a lifetime requires understanding the service’s state and dependencies.

This article examines the built-in .NET container using ordinary type-based registrations.

How Do the Three Lifetimes Differ?

Registration Creation and reuse
AddTransient Creates a new instance each time the service is resolved from the container.
AddScoped Creates an instance when first resolved within a scope. Subsequent resolutions in that scope reuse it.
AddSingleton Shares one instance for that registration within the same container. With type-based registration, the first resolution normally creates it.

During ordinary ASP.NET Core request processing, each HTTP request has its own scope. Two services handling the same request can therefore receive the same scoped dependency. A later request receives a different scope and a different scoped instance.

Dependency injection in ASP.NET Core

Observe the Difference Across Two Requests

Create a Minimal API project:

dotnet new web -n LifetimeDemo
cd LifetimeDemo

Replace Program.cs with the following code. Each service has an identifier, and the endpoint resolves each service twice:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddTransient<TransientStamp>();
builder.Services.AddScoped<ScopedStamp>();
builder.Services.AddSingleton<SingletonStamp>();

var app = builder.Build();

app.MapGet("/lifetimes", (HttpContext context) => new
{
    transient = ReadPair<TransientStamp>(context.RequestServices),
    scoped = ReadPair<ScopedStamp>(context.RequestServices),
    singleton = ReadPair<SingletonStamp>(context.RequestServices)
});

app.Run();

static Guid[] ReadPair<T>(IServiceProvider services) where T : Stamp
{
    return
    [
        services.GetRequiredService<T>().Id,
        services.GetRequiredService<T>().Id
    ];
}

public abstract class Stamp
{
    public Guid Id { get; } = Guid.NewGuid();
}

public sealed class TransientStamp : Stamp { }
public sealed class ScopedStamp : Stamp { }
public sealed class SingletonStamp : Stamp { }

Run the application:

dotnet run --urls http://localhost:5000

Open http://localhost:5000/lifetimes twice. Each response contains three arrays, each holding two GUIDs.

The following table shows the expected pattern. The labels represent different GUIDs:

Lifetime Two resolutions in the first request Two resolutions in the second request
Transient T1 and T2 T3 and T4
Scoped S1 and S1 S2 and S2
Singleton G1 and G1 G1 and G1

Transient produces different instances even within one request. Scoped shares an instance within the request’s scope. Singleton returns the same instance across both requests, assuming the same application and container remain running.

Official service lifetime definitions

This example deliberately uses RequestServices to make resolution behavior visible. In ordinary application code, receive dependencies through constructor injection or service parameters on an endpoint.

Transient Means a New Resolution, Not Every Method Call

Suppose a service receives a transient dependency through its constructor and stores it in a field. Calling methods on that service again does not create another dependency. Resolving an object from the container and calling a method are different operations.

If the consumer is a singleton, it may retain that transient dependency for its own lifetime. This combination is not automatically invalid, but the dependency must be suitable for long-term—and potentially concurrent—use.

Guidance on captive dependencies

Singletons and Request-Specific Information

Imagine a singleton storing the current user’s identifier in a CurrentUserId field. The first user’s request sets the value. Before that request finishes, a second user’s request changes it. The first request may now continue using the second user’s information.

This illustrates why request-specific state should not be placed in a shared object without an appropriate design. A singleton must support safe concurrent use. Selecting the singleton lifetime does not make the container lock its methods.

Singleton lifetime and thread safety

A singleton is also limited to its container. If an application runs on three replicas, those replicas do not share one in-memory object. Coordinating state across application instances is a separate concern from a service’s DI lifetime.

Why Scoped Does Not Guarantee Thread Safety

Scoped determines which consumers receive the same instance. It does not guarantee that concurrent method calls on that instance are safe.

For example, AddDbContext registers a DbContext as scoped by default. However, DbContext does not support multiple operations running concurrently on the same instance. Starting two queries with Task.WhenAll against that context within one request does not become safe because the context is scoped.

Await operations on the same context sequentially, or use independent contexts with appropriate lifetime management when parallel work is required.

DbContext lifetime and threading limitations

What Happens When a Singleton Depends on a Scoped Service?

Suppose ReportService is a singleton and receives a scoped service containing request state through its constructor.

ReportService is shared across requests, while its dependency is intended to belong to one scope. Retaining that dependency in the singleton breaks the expected scope boundary.

When scope validation is enabled, the container rejects this direct dependency relationship. Validation is enabled in the usual Development configuration. Disabling it does not resolve the design problem.

Rules for consuming scoped services from singletons

The appropriate solution depends on the consumer’s responsibility. If it belongs to request processing and depends on request state, it may need to be scoped itself. If it is genuinely long-lived, it can create a scope for an independent operation and use the dependency only within that operation.

How Should a BackgroundService Consume Scoped Dependencies?

A hosted service registered with AddHostedService is a singleton. A new scope is not automatically created for each piece of work it performs.

For a worker processing queued jobs, we can create a scope for each unit of processing.

Inject IServiceScopeFactory into the worker and use a pattern like the following at the processing boundary. This fragment assumes that IJobProcessor is a registered scoped service:

await using var scope = scopeFactory.CreateAsyncScope();

var processor = scope.ServiceProvider
    .GetRequiredService<IJobProcessor>();

await processor.ProcessAsync(stoppingToken);

Processing must complete before the scope is disposed. Keeping the processor outside the scope, or starting its work without awaiting it, can separate the operation’s lifetime from the lifetime of its resources.

Choose the scope boundary to match a unit of work: a message, a job, or a defined batch. Creating a scope does not itself provide a database transaction, retry behavior, or protection against duplicate processing.

Using scoped services within a BackgroundService

When Does Disposal Happen?

For disposable instances created by the container:

  • Scoped and transient instances are disposed when their resolving scope ends. Returning from a method does not immediately dispose them.
  • Singleton instances are disposed when the container is disposed, normally during application shutdown.

A disposable transient resolved from the root provider can also be retained until the container is disposed. With AddSingleton(new MyService()), we create the instance ourselves and remain responsible for disposing it.

Resource ownership and disposal guidance

Does Scoped Always Mean One HTTP Request?

Scoped means one instance per scope. An HTTP request is one possible scope boundary.

Workers and console applications can create scopes explicitly. In server-side interactive Blazor, the scope used by interactive components can follow a circuit’s lifetime and outlast an individual HTTP request. The rules of an ordinary Web API should therefore not be applied to every hosting model without checking its scope behavior.

Service lifetimes in Blazor

How Should We Choose a Lifetime?

Start with how long the service’s information remains valid:

Service requirement Lifetime to consider Important condition
An independent instance for each resolution Transient Construction cost and owned resources are acceptable.
Shared state within a unit of work Scoped The scope boundary matches the unit of work.
Long-lived shared behavior or data Singleton State, concurrency, and dependencies support that lifetime.

Before registering a service, ask:

  • Does it retain information specific to a request or user?
  • Do multiple consumers need the same instance during one operation?
  • What lifetimes and concurrency limitations do its dependencies have?
  • Who owns its resources, and when should they be released?

If the only reason for choosing Singleton is reducing object creation, measure the actual construction cost. Saving allocations is useful when it does not introduce invalid state, unintended dependency retention, or concurrency problems.