Dependency Injection is one of the core features of modern ASP.NET Core applications. It allows developers to create loosely coupled applications by providing dependencies to classes rather than having those classes create their own dependencies.
ASP.NET Core includes a built-in Dependency Injection container, making it easy to register and resolve services throughout an application.
However, registering a service is only part of the process. One of the most important decisions developers must make is choosing the appropriate service lifetime.
ASP.NET Core provides three primary service lifetimes:
- Singleton
- Scoped
- Transient
Choosing the wrong lifetime can lead to unexpected behavior, memory issues, concurrency problems, stale data, or runtime exceptions.
In this article, we'll understand each lifetime with practical C# examples and explore when to use them in real-world ASP.NET Core applications.
1. What Is Dependency Injection?
Dependency Injection is a design principle where a class receives the objects it depends on from an external source rather than creating them itself.
Consider a service that retrieves customer information.
Without Dependency Injection:
public class CustomerService
{
private readonly CustomerRepository _repository;
public CustomerService()
{
_repository = new CustomerRepository();
}
}
Here, CustomerService directly creates its repository.
This creates tight coupling between the two classes. If the repository implementation changes, the service may also need to change.
With Dependency Injection:
public class CustomerService
{
private readonly ICustomerRepository _repository;
public CustomerService(
ICustomerRepository repository)
{
_repository = repository;
}
}
Now the service depends on an abstraction.
ASP.NET Core can provide the required implementation through its DI container.
This makes the application easier to maintain, test, and extend.
2. Understanding Service Lifetimes
When registering a service, ASP.NET Core needs to know how long that service instance should exist.
This is called its lifetime.
For example:
builder.Services.AddSingleton<IEmailService, EmailService>(); builder.Services.AddScoped<ICustomerService, CustomerService>(); builder.Services.AddTransient<IReportService, ReportService>();
Each registration tells the DI container how to create and reuse instances.
Let's examine the three lifetimes.
3. Transient Lifetime
A transient service is created every time it is requested from the DI container.
Registration:
builder.Services.AddTransient<IProductService, ProductService>();
If the service is requested multiple times, a new instance is created for each resolution.
Example
public class OperationService
{
public Guid InstanceId { get; } = Guid.NewGuid();
}
Register it:
builder.Services.AddTransient<OperationService>();
Inject it into a controller:
public class HomeController : Controller
{
private readonly OperationService _service1;
private readonly OperationService _service2;
public HomeController(
OperationService service1,
OperationService service2)
{
_service1 = service1;
_service2 = service2;
}
public IActionResult Index()
{
return Content(
$"Service 1: {_service1.InstanceId}\n" +
$"Service 2: {_service2.InstanceId}");
}
}
Because the service is transient, the two injected instances will normally have different IDs.
Example output:
Service 1: 0f1a7b52-91d0-4d14-8d53-37e4b2209f1c Service 2: 74f8d30b-9b24-4a6e-a210-8b7d5c192d21
When should you use Transient?
Transient services are suitable for:
- Lightweight services
- Stateless business logic
- Formatting services
- Small utility services
- Services that should not retain state between resolutions
For example:
builder.Services.AddTransient<IPriceCalculator, PriceCalculator>();
A price calculator that performs calculations without maintaining internal state is a reasonable candidate for a transient lifetime.
Transient does not automatically mean the service is disposable after every method call. Instances created by the DI container are generally disposed when their owning scope is disposed, or when the root container is disposed for root-resolved instances.
4. Scoped Lifetime
A scoped service is created once per dependency injection scope.
In a typical ASP.NET Core web application, a scope is created for each HTTP request.
This means that if the same scoped service is injected multiple times during a request, those injections normally refer to the same instance.
Registration:
builder.Services.AddScoped<ICustomerService, CustomerService>();
Example
public class OperationService
{
public Guid InstanceId { get; } = Guid.NewGuid();
}
Register it:
builder.Services.AddScoped<OperationService>();
Inject it into the same controller:
public class HomeController : Controller
{
private readonly OperationService _service1;
private readonly OperationService _service2;
public HomeController(
OperationService service1,
OperationService service2)
{
_service1 = service1;
_service2 = service2;
}
public IActionResult Index()
{
return Content(
$"Service 1: {_service1.InstanceId}\n" +
$"Service 2: {_service2.InstanceId}");
}
}
Both instances will have the same ID because they belong to the same request scope.
If another HTTP request comes in, a new scoped instance will be created.
When should you use Scoped?
Scoped services are ideal for:
- Business services used during a request
- Repository implementations
- Database access services
- User-specific operations
- Services that depend on EF Core DbContext
For example:
builder.Services.AddScoped<IOrderService, OrderService>(); builder.Services.AddScoped<IOrderRepository, OrderRepository>();
This allows the services to share scoped dependencies, such as the same DbContext, during a request.
5. Singleton Lifetime
A singleton service is created once for the lifetime of the application's DI container and reused whenever it is requested.
Registration:
builder.Services.AddSingleton<IApplicationSettings, ApplicationSettings>();
Example
public class OperationService
{
public Guid InstanceId { get; } = Guid.NewGuid();
}
Register it:
builder.Services.AddSingleton<OperationService>();
Now multiple requests and multiple injections will use the same service instance.
Example output from different requests:
Request 1: 0f1a7b52-91d0-4d14-8d53-37e4b2209f1c Request 2: 0f1a7b52-91d0-4d14-8d53-37e4b2209f1c Request 3: 0f1a7b52-91d0-4d14-8d53-37e4b2209f1c
The instance remains the same until the application shuts down or the container is disposed.
When should you use Singleton?
Singleton services are suitable for:
- Immutable configuration-related services
- Shared caches
- Stateless services that are thread-safe
- Application-wide reusable resources
- Services that maintain safe shared state
For example:
builder.Services.AddSingleton<ICacheService, CacheService>();
A cache service can be singleton if its implementation is designed to safely handle concurrent access.
However, singleton services must be designed carefully because multiple requests can access the same instance simultaneously.
6. Comparing Singleton, Scoped, and Transient
The easiest way to understand the differences is through a comparison.
LifetimeInstance creationReuseTypical usageTransientEach DI resolutionNo reuse guaranteeLightweight utilitiesScopedOnce per scopeWithin the same scopeBusiness services, repositories, DbContextSingletonOnce per containerAcross scopesShared caches, thread-safe services
Visual representation
flowchart TD
A[Application Starts] --> B[Singleton Instance]
A --> C[HTTP Request 1]
A --> D[HTTP Request 2]
C --> E[Scoped Instance 1]
C --> F[Transient Instance 1]
C --> G[Transient Instance 2]
D --> H[Scoped Instance 2]
D --> I[Transient Instance 3]
D --> J[Transient Instance 4]
B -. reused .-> C
B -. reused .-> D
The singleton is shared across requests.
Each request gets its own scoped service.
Transient services are created whenever the DI container resolves them, so multiple resolutions may produce different instances even within the same request.
7. Why Entity Framework Core DbContext Is Scoped
One of the most important examples of service lifetime selection is DbContext.
In ASP.NET Core, the recommended registration is usually:
builder.Services.AddDbContext<ApplicationDbContext>(
options =>
options.UseNpgsql(
builder.Configuration.GetConnectionString(
"DefaultConnection")));
AddDbContext registers the context as scoped by default.
Why?
Because a DbContext is designed to represent a unit of work.
During a request:
- The application creates the DbContext.
- Queries retrieve entities.
- EF Core tracks entity changes.
- Business operations modify entities.
SaveChangesAsync()persists changes.- The request scope ends.
- The DbContext is disposed.
This provides a convenient lifecycle for web applications.
Why not Singleton DbContext?
A DbContext is not thread-safe.
If the same DbContext instance is shared across multiple concurrent requests, operations can interfere with each other and produce exceptions or incorrect behavior.
For example, registering DbContext as singleton is a mistake:
// Do not register DbContext this way. builder.Services.AddSingleton<ApplicationDbContext>();
This can lead to:
- Concurrent access errors
- Incorrect entity tracking
- Stale data
- Memory growth from tracked entities
- Database operation conflicts
Use the standard scoped registration unless you have a specific scenario requiring a different design.
8. The Captive Dependency Problem
One of the most common DI lifetime mistakes is injecting a scoped service into a singleton.
Consider:
public class ReportService
{
private readonly ApplicationDbContext _context;
public ReportService(ApplicationDbContext context)
{
_context = context;
}
}
Suppose we register it as a singleton:
builder.Services.AddSingleton<ReportService>();
But DbContext is scoped.
Now the singleton depends on a scoped service.
This creates a problem because the singleton lives for the entire application lifetime, while the DbContext should live only for a particular scope.
The scoped dependency can effectively become retained by the singleton, causing it to live much longer than intended.
This is often called a captive dependency.
When scope validation is enabled, ASP.NET Core can detect and throw an exception for this invalid dependency relationship.
Incorrect registration
builder.Services.AddScoped<ApplicationDbContext>(); builder.Services.AddSingleton<ReportService>();
Correct approach
If the service uses DbContext as part of request processing, register the service as scoped:
builder.Services.AddScoped<ReportService>();
Or if a background service needs database access, create a scope or use IServiceScopeFactory / IDbContextFactory<TContext> appropriately rather than holding a scoped DbContext inside a singleton.
9. Service Lifetimes in Background Services
Background services are generally registered as singletons.
For example:
builder.Services.AddHostedService<EmailBackgroundService>();
But what if the background service needs a scoped service such as a repository or DbContext?
You should not directly inject a scoped dependency into the background service constructor.
Instead, create a scope when processing work.
Example
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
public class EmailBackgroundService : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<EmailBackgroundService> _logger;
public EmailBackgroundService(
IServiceScopeFactory scopeFactory,
ILogger<EmailBackgroundService> logger)
{
_scopeFactory = scopeFactory;
_logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
using var scope = _scopeFactory.CreateScope();
var emailService = scope.ServiceProvider
.GetRequiredService<IEmailService>();
await emailService.ProcessPendingEmailsAsync(
stoppingToken);
await Task.Delay(
TimeSpan.FromMinutes(1),
stoppingToken);
}
}
}
In this example:
- The background worker itself is long-lived.
- A new scope is created for each processing iteration.
- Scoped services are resolved within that scope.
- The scope is disposed when the iteration finishes.
This prevents scoped dependencies from being retained indefinitely.
In production, background workers should also handle exceptions, cancellation, retry strategies, and appropriate scheduling rather than relying solely on a simple delay loop.
10. Does Transient Mean Thread-Safe?
Not necessarily.
A transient service gets a new instance when the container resolves it, but that does not automatically make the service thread-safe.
For example:
public class CounterService
{
private int _count;
public void Increment()
{
_count++;
}
}
Even if this service is transient, the same instance could still be shared by multiple consumers or used concurrently.
Thread safety depends on how the service is used and whether it accesses shared state.
Likewise, singleton services are not automatically thread-safe.
If a singleton maintains mutable state, you must consider concurrent requests and use appropriate synchronization or thread-safe data structures.
For example:
using System.Collections.Concurrent;
public class RequestCounterService
{
private readonly ConcurrentDictionary<string, int> _counters =
new();
public void Increment(string key)
{
_counters.AddOrUpdate(
key,
1,
(_, count) => count + 1);
}
}
This is safer for concurrent access than using a normal dictionary with unsynchronized updates.
11. How to Choose the Correct Lifetime
Before registering a service, consider the following questions.
Does the service maintain shared state?
If it stores application-wide data, a singleton may be appropriate — provided that the state is managed safely.
Does the service depend on DbContext?
In most web application scenarios, a scoped lifetime is appropriate.
Is the service lightweight and stateless?
Transient can be a good choice, although scoped may also be perfectly reasonable depending on the application.
Does the service need to share data within one HTTP request?
Scoped is usually the appropriate choice.
Is the service used by a background worker?
Background workers are long-lived, so scoped dependencies should be resolved through explicit scopes.
Is the service thread-safe?
This is especially important for singleton services.
A lifetime decision should consider not only how often an object is created but also how long it retains data, what dependencies it holds, and how it behaves under concurrent access.
12. Practical Registration Example
Let's look at a typical ASP.NET Core application registration.
var builder = WebApplication.CreateBuilder(args);
// Database
builder.Services.AddDbContext<ApplicationDbContext>(
options =>
options.UseNpgsql(
builder.Configuration.GetConnectionString(
"DefaultConnection")));
// Repositories
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddScoped<ICustomerRepository, CustomerRepository>();
// Business services
builder.Services.AddScoped<IProductService, ProductService>();
builder.Services.AddScoped<ICustomerService, CustomerService>();
// Lightweight utility
builder.Services.AddTransient<IEmailTemplateRenderer, EmailTemplateRenderer>();
// Shared application cache
builder.Services.AddSingleton<ICacheService, CacheService>();
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
This is a common arrangement for a database-backed ASP.NET Core application:
- DbContext: Scoped
- Repositories: Scoped
- Business services: Scoped
- Stateless utilities: Transient
- Shared, thread-safe cache: Singleton
The exact registrations should depend on the behavior and dependencies of your services rather than simply following a fixed template.
Conclusion
Dependency Injection lifetimes are more than just registration options in ASP.NET Core. They determine how objects are created, reused, disposed, and shared throughout your application.
Transient services are useful for lightweight dependencies that should not be reused by the container across resolutions.
Scoped services are ideal for request-specific operations, repositories, and database access through Entity Framework Core.
Singleton services are useful for application-wide shared components, but they must be designed carefully to handle concurrent access and avoid retaining scoped dependencies.
Choosing the correct lifetime helps prevent memory issues, concurrency problems, unexpected state sharing, and dependency-related runtime errors.
When designing your application, remember this simple guideline:
Use Scoped for most business and database services, Transient for lightweight stateless utilities, and Singleton only for genuinely application-wide services that are safe to share.
Understanding these lifetimes will help you write cleaner, more predictable, and more maintainable ASP.NET Core applications.