Service LIfetime
Everything about Service Lifetime
Service Lifetimes in ASP.NET Core
Understand Transient, Scoped, and Singleton services, how the dependency injection container manages their instances, and how to choose the right lifetime for reliable, secure, and scalable .NET applications.
- Category: .NET Fundamentals
- Difficulty: Intermediate
- Target framework: .NET 10
- Prerequisites: C# classes and interfaces, constructors, object
creation, Dependency Injection (DI),
Program.cs, and basic ASP.NET Core controllers and HTTP requests.
Learning Outcomes
By the end of this module, you will be able to:
- Explain what service lifetimes are and why they exist.
- Differentiate Transient, Scoped, and Singleton services.
- Register services using
AddTransient,AddScoped, andAddSingleton. - Predict when service instances are created, reused, and disposed.
- Understand how service lifetimes interact with HTTP requests.
- Identify and fix captive dependencies and lifetime mismatches.
- Apply the right lifetime to database contexts, business services, caches, and background workers.
- Test service lifetimes through a running ASP.NET Core application.
- Answer service-lifetime interview questions.
- Make safe, performance-conscious lifetime decisions in production systems.
1. Introduction
Imagine that you are building an e-commerce application using ASP.NET Core. The application contains services for managing products, processing orders, accessing a database, sending emails, and caching frequently requested information.
Each service is an object created from a C# class. The application needs to decide whether to create a new object whenever it is requested, reuse an object during an HTTP request, or share one object throughout the application's lifetime.
This decision is called a service lifetime.
What is a service lifetime?
A service lifetime defines how long a service instance is retained and when the dependency injection (DI) container provides a new instance versus reusing an existing one.
Comparison of Service Lifetimes
| Lifetime | Registration Method | General Behavior |
|---|---|---|
| Transient | AddTransient | Creates a new instance each time the service is resolved. |
| Scoped | AddScoped | Creates one instance per scope, typically one per HTTP request in a web application. |
| Singleton | AddSingleton | Uses one instance per service registration in a given dependency injection (DI) container. |
These lifetimes determine object reuse, disposal, and important aspects of thread safety and resource management.
Why do service lifetimes exist?
Without a lifetime-management mechanism, developers would need to decide manually when every dependency should be created, reused, and disposed.
public class ProductsController
{
private readonly ProductService _productService;
public ProductsController()
{
// Manually creating the dependency tightly couples this class to ProductService.
_productService = new ProductService();
}
}
With dependency injection, the controller receives the dependency from the framework:
public class ProductsController
{
private readonly IProductService _productService;
public ProductsController(IProductService productService)
{
_productService = productService;
}
}
DI raises another important question: How long should the injected object live?
- A lightweight formatting helper might be created whenever needed.
- A database context should usually be limited to a request or another explicitly managed scope.
- A shared in-memory cache might need to serve many requests using the same instance.
Important: A service lifetime is not simply a performance setting. It is also an object ownership, state-management, and correctness decision.
2. Real-Life Analogy: A Restaurant
Imagine a restaurant with three types of resources.
Transient --- A fresh order slip
Whenever a new order is placed, the restaurant prepares a new order slip. Each operation receives its own slip rather than reusing an unrelated customer's slip.
In ASP.NET Core: A new service instance is created each time the service is resolved.
Scoped --- One table's bill
A table's bill is shared among the waiters handling that table's current meal. Another table has its own bill. When the meal ends, the bill's lifecycle ends.
In ASP.NET Core: One service instance is normally shared throughout a single HTTP request when resolved from that request's scope.
Singleton --- The restaurant's central menu board
Many customers and waiters refer to the same central menu board. The board remains available instead of being recreated for every table.
In ASP.NET Core: One service instance is shared by resolutions from the same DI container, subject to the registration and container lifetime.
The analogy helps explain the difference, but real service lifetimes depend on DI scopes and object ownership, not restaurant operations.
3. Architecture Diagram
How the three lifetimes behave
Instance sharing across HTTP requests
AT1andAT2represent separate transient resolutions.ASandBSare separate scoped instances because they belong to different request scopes.Srepresents the shared singleton instance.
An HTTP request normally has a scope, but a manually created scope or a background worker can have its own scope too.
4. Concept Explanation
4.1 What is a service?
A service is a class that performs a particular responsibility in an application.
public interface IProductService
{
string GetProductName(int id);
}
public class ProductService : IProductService
{
public string GetProductName(int id)
{
return $"Product {id}";
}
}
Here, IProductService defines a contract, ProductService implements
that contract, and GetProductName() represents the service's behavior.
A controller, another service, or a background worker can depend on
IProductService.
4.2 What is the DI container?
The DI container tracks registered services and creates or reuses their instances according to their registrations and the scopes in which they are resolved.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IProductService, ProductService>();
var app = builder.Build();
app.MapGet("/products/{id:int}", (int id, IProductService service) =>
service.GetProductName(id));
app.Run();
When an HTTP request reaches the endpoint, ASP.NET Core supplies the
required IProductService through DI. The developer does not need to
write new ProductService() in the endpoint.
4.3 Transient lifetime
A transient service is registered using AddTransient.
builder.Services.AddTransient<IProductService, ProductService>();
Whenever the container resolves IProductService, it creates a new
ProductService instance.
var first = provider.GetRequiredService<IProductService>();
var second = provider.GetRequiredService<IProductService>();
Console.WriteLine(ReferenceEquals(first, second)); // False
Assuming the registration above and that no other mechanism returns a shared instance, the references point to different objects.
When is transient useful?
- Stateless formatting helpers.
- Lightweight calculation services.
- Small mapping or transformation operations.
- Services that should not preserve state between independent resolutions.
Advantages - Helps avoid unintended sharing of mutable instance state. - Simple lifetime semantics. - Appropriate for small, inexpensive objects.
Potential drawbacks - Frequent resolutions can create many objects. - Expensive initialization may be repeated. - Transient dependencies captured by longer-lived services may live much longer than expected.
Tip: Transient does not mean the object is immediately destroyed after a method call. It means a new instance is provided for each resolution. Disposal depends on ownership and the scope or container that created it.
4.4 Scoped lifetime
A scoped service is registered using AddScoped.
builder.Services.AddScoped<IProductService, ProductService>();
The DI container creates an instance the first time the service is resolved in a scope. Later resolutions of that service registration in the same scope return the same instance.
app.MapGet("/demo", (
IProductService first,
IServiceProvider provider) =>
{
var second = provider.GetRequiredService<IProductService>();
return new
{
SameInstance = ReferenceEquals(first, second)
};
});
If IProductService is scoped and provider is the request-scoped
provider, SameInstance is true. A new HTTP request gets a different
scoped instance.
When is scoped useful?
- Entity Framework Core
DbContext. - Business operations that share request-specific state.
- Services that coordinate work within one request.
- Request-level unit-of-work patterns.
Advantages - Reuses the same instance within the scope. - Avoids creating a new object for every resolution inside that scope. - Supports request-bound resource management.
Potential drawbacks - Scoped instances can be used incorrectly outside their scope. - A scoped service must not be directly captured by a singleton. - A scope that is never disposed can retain resources longer than intended.
Important: Scoped does not always mean one instance per HTTP request. It means one instance per DI scope. Applications can explicitly create additional scopes outside HTTP requests.
4.5 Singleton lifetime
A singleton service is registered using AddSingleton.
builder.Services.AddSingleton<IProductService, ProductService>();
The container creates or obtains the registered singleton instance and reuses it for subsequent resolutions from that container. For type-based singleton registration, construction generally occurs when the service is first resolved. Factory-based and instance-based registrations have their own creation timing.
var first = provider.GetRequiredService<IProductService>();
var second = provider.GetRequiredService<IProductService>();
Console.WriteLine(ReferenceEquals(first, second)); // True
When is singleton useful?
- Thread-safe in-memory caches.
- Immutable application-wide lookup data.
- Stateless shared infrastructure services.
- Expensive, reusable components designed for concurrent use.
Advantages - Avoids repeated creation of the same shared component. - Can reduce repeated initialization costs. - Allows shared application-level state when explicitly designed for it.
Potential drawbacks - The object may remain alive for the entire container lifetime. - Mutable state can be shared across concurrent requests. - Retaining large object graphs can increase memory use. - A singleton can accidentally capture scoped services.
Warning: Singleton services are not automatically thread-safe. ASP.NET Core can resolve a singleton concurrently for many requests. Protect mutable shared state or, preferably, design the service to be stateless or immutable.
4.6 Service lifetimes at a glance
| Characteristic | Transient | Scoped | Singleton |
|---|---|---|---|
| Registration | AddTransient | AddScoped | AddSingleton |
| Reuse | A new instance each time the service is resolved | One instance per scope | One instance per service registration in the DI container |
| Typical web behavior | New instance whenever resolved | Shared within one HTTP request scope | Shared across requests |
| State isolation | Separate instances | Isolated between scopes | State is shared by all consumers of that instance |
| Thread safety | Depends on how the instance and its dependencies are used | Depends on how the instance and its dependencies are used | Especially important when mutable state is shared across concurrent requests |
| Typical example | Lightweight formatter | DbContext (commonly scoped in ASP.NET Core) | Thread-safe memory cache |
| Common risk | Excessive allocations if resolved frequently | Incorrect scope usage or resolving scoped services from a singleton | Race conditions or unexpected behavior caused by shared mutable state |
4.7 Service lifetime versus object lifetime
The registered lifetime determines how DI reuses the service. The actual object's lifetime also depends on references and ownership.
A transient object can remain alive if another object holds a reference to it. A disposable transient resolved from a DI scope may be retained by that scope so that DI can dispose of it when the scope ends.
Likewise, a singleton instance may hold references to other objects and thereby extend their effective lifetimes.
This is why service lifetime decisions should consider the entire dependency graph, not just one registration.
4.8 Service lifetime versus HTTP request lifetime
These are related but not identical concepts:
- HTTP request lifetime: The duration of processing one incoming HTTP request.
- DI scope lifetime: The duration during which a scoped service instance is shared.
- Object lifetime: How long an object remains reachable and usable.
- Container lifetime: How long a DI container and its managed services remain active.
In ordinary ASP.NET Core request processing, the request scope is created for the request and disposed when request processing finishes. Background services and manually created scopes have different boundaries.
4.9 Service lifetime and state
Imagine a service with a mutable field:
public class ProductService
{
public int RequestCount { get; private set; }
public void Increment()
{
RequestCount++;
}
}
The behavior depends on the lifetime:
- Transient: Each separately resolved instance maintains its own counter.
- Scoped: Resolutions in the same scope share a counter.
- Singleton: All consumers resolving that singleton share its counter.
This example uses mutable state for learning purposes. In a real concurrent application, the singleton's increment operation is not thread-safe. Also, a scoped counter is not automatically a reliable measure of HTTP requests if it can be resolved in non-request scopes.
4.10 What about AddDbContext?
Entity Framework Core's standard registration is scoped:
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")));
A DbContext is designed for a short unit of work and is not
thread-safe. It should not be shared across concurrent operations.
A single request may retrieve products and create an order using
services that share the same scoped AppDbContext. This can be useful
when they intentionally participate in one unit of work.
Do not make a DbContext singleton. Also avoid running simultaneous
operations on the same context instance.
4.11 Why the correct lifetime matters
Suppose a singleton OrderService depends on a scoped AppDbContext.
The singleton can outlive the scope in which the context was created.
Depending on resolution and validation, this can cause a
lifetime-validation error or result in incorrect reuse of a context
beyond its intended unit of work.
The fix is usually to make OrderService scoped if its responsibilities
are request-bound, or to have a background or long-running service
create an explicit scope for each unit of work.
The right solution depends on the design. Do not simply change the database context to singleton to silence an error.
5. Important Terminology
| Term | Meaning | Example |
|---|---|---|
| Service | A class that performs an application responsibility | ProductService |
| Interface | A contract that defines available operations | IProductService |
| Dependency Injection | Supplying dependencies to a class rather than constructing them manually | Constructor injection |
| DI container | Manages registered services and their resolutions | builder.Services |
| Service descriptor | Metadata describing a registered service | Service type, implementation, lifetime |
| Transient | A new instance for each resolution | AddTransient |
| Scoped | One instance per DI scope | AddScoped |
| Singleton | One shared instance per registration and container | AddSingleton |
| Scope | A boundary for scoped instances and their disposal | HTTP request scope |
| Resolution | Requesting a service from the DI container | GetRequiredService<T>() |
| Disposal | Releasing resources owned by an object | Dispose() |
| Thread safety | Correct behavior when multiple threads access an object | Synchronization around shared state |
| Captive dependency | A shorter-lived dependency retained by a longer-lived service | Singleton holding a scoped service |
| Object graph | A service and the dependencies it references | Controller → service → repository |
| Factory registration | A delegate used to create a service instance | AddSingleton<T>(sp => ...) |
| Unit of work | A bounded operation that coordinates related data changes | Processing an order |
6. How It Works Internally
Step 1: Application startup
ASP.NET Core creates a service collection through the application builder.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient<IEmailFormatter, EmailFormatter>();
builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddSingleton<IProductCache, ProductCache>();
Each registration describes how the container should resolve a service.
Step 2: Build the application
var app = builder.Build();
The application builds its service provider using the registered services. The container can validate service registrations and dependency relationships when validation is enabled.
Step 3: A request arrives
A request reaches an endpoint or controller. ASP.NET Core resolves its required parameters and dependencies using the appropriate service provider.
Step 4: The container applies the lifetime
- Transient: create an instance for that resolution.
- Scoped: reuse the instance in the current scope or create it on first resolution.
- Singleton: reuse the singleton instance for that registration.
Step 5: The service performs its work
The resolved service executes its business logic, possibly using its own dependencies.
Step 6: Scope disposal
When an HTTP request's scope ends, the container disposes of disposable services it owns in that scope. The application host disposes of the root provider during shutdown, which handles container-owned singleton services.
Exact disposal behavior depends on how objects were created and who owns them. A service manually constructed outside DI is not automatically owned by DI.
Sequence diagram
The diagram shows the common request lifecycle. A particular endpoint may resolve more than one service, and the container may reuse additional scoped or singleton dependencies.
What happens with repeated resolutions?
var first = scope.ServiceProvider
.GetRequiredService<IOrderService>();
var second = scope.ServiceProvider
.GetRequiredService<IOrderService>();
Console.WriteLine(ReferenceEquals(first, second)); // True
The container caches the scoped instance for that service registration within the scope. If another scope resolves the same service, it gets a different instance.
Note: These examples use
IServiceScopecreated from a valid provider. Avoid building a second service provider during normal registration merely to resolve dependencies; doing so can create duplicate singleton instances and confusing ownership.
7. Syntax
Registering a transient service
builder.Services.AddTransient<IEmailFormatter, EmailFormatter>();
builder: The application builder.Services: The service collection.AddTransient: Registers a transient lifetime.IEmailFormatter: The service contract.EmailFormatter: The implementation.
The interface and implementation types must be compatible.
Registering a scoped service
builder.Services.AddScoped<IOrderService, OrderService>();
Use this when the service should be reused within a scope and isolated from other scopes.
Registering a singleton service
builder.Services.AddSingleton<IProductCache, ProductCache>();
Use this when the implementation is suitable for sharing across the container's lifetime.
Registering a service without an interface
Interfaces are not mandatory.
builder.Services.AddScoped<OrderService>();
A consumer can then request OrderService directly. Interfaces can
improve separation of concerns and testability.
Registering a pre-created instance
var cache = new ProductCache();
builder.Services.AddSingleton<IProductCache>(cache);
The supplied instance is used as the singleton. The application created
cache itself, so it should also consider how that instance is owned
and disposed. The container does not automatically assume ownership of
an externally supplied singleton instance in the same way it manages
instances it creates.
Registering with a factory
builder.Services.AddSingleton<IProductCache>(sp =>
new ProductCache());
The factory receives the service provider. This is useful when construction requires additional configuration or dependencies.
A factory does not change the registered lifetime: a singleton factory is used to obtain the singleton instance, while a transient factory creates a new instance on each resolution.
8. Code Examples
All examples use C# and ASP.NET Core 9-compatible patterns.
8.1 Simple example: Compare all three lifetimes
Create a class that records a unique identifier:
public class TransientTracker
{
public Guid Id { get; } = Guid.NewGuid();
}
public class ScopedTracker
{
public Guid Id { get; } = Guid.NewGuid();
}
public class SingletonTracker
{
public Guid Id { get; } = Guid.NewGuid();
}
Register and test the lifetimes:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient<TransientTracker>();
builder.Services.AddScoped<ScopedTracker>();
builder.Services.AddSingleton<SingletonTracker>();
var app = builder.Build();
app.MapGet("/lifetimes", (
TransientTracker transient1,
ScopedTracker scoped1,
SingletonTracker singleton1,
IServiceProvider provider) =>
{
var transient2 =
provider.GetRequiredService<TransientTracker>();
var scoped2 =
provider.GetRequiredService<ScopedTracker>();
var singleton2 =
provider.GetRequiredService<SingletonTracker>();
return Results.Ok(new
{
TransientSame = ReferenceEquals(transient1, transient2),
ScopedSame = ReferenceEquals(scoped1, scoped2),
SingletonSame = ReferenceEquals(singleton1, singleton2),
TransientId1 = transient1.Id,
TransientId2 = transient2.Id,
ScopedId1 = scoped1.Id,
ScopedId2 = scoped2.Id,
SingletonId1 = singleton1.Id,
SingletonId2 = singleton2.Id
});
});
app.Run();
Expected behavior:
- Transient references differ.
- Scoped references match within the request.
- Singleton references match within the container.
The endpoint's injected IServiceProvider represents the request's
service provider, so the scoped resolution stays within the current
request scope.
8.2 Intermediate example: Track service instances across requests
Make several requests to /lifetimes.
- The transient ID changes for each independent resolution.
- The scoped ID changes between request scopes.
- The singleton ID remains the same while the application uses the same DI container.
The IDs demonstrate instance reuse, not the number of active HTTP requests or users.
8.3 Production example: Order processing
A common architecture uses a scoped order service and repository backed by a scoped EF Core context.
public sealed record CreateOrderRequest(
int ProductId,
int Quantity);
public interface IOrderRepository
{
Task<int> CreateAsync(
CreateOrderRequest request,
CancellationToken cancellationToken);
}
public sealed class OrderRepository : IOrderRepository
{
private readonly AppDbContext _dbContext;
public OrderRepository(AppDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<int> CreateAsync(
CreateOrderRequest request,
CancellationToken cancellationToken)
{
var order = new Order
{
ProductId = request.ProductId,
Quantity = request.Quantity
};
_dbContext.Orders.Add(order);
await _dbContext.SaveChangesAsync(cancellationToken);
return order.Id;
}
}
public interface IOrderService
{
Task<int> CreateAsync(
CreateOrderRequest request,
CancellationToken cancellationToken);
}
public sealed class OrderService : IOrderService
{
private readonly IOrderRepository _repository;
public OrderService(IOrderRepository repository)
{
_repository = repository;
}
public Task<int> CreateAsync(
CreateOrderRequest request,
CancellationToken cancellationToken)
{
if (request.ProductId <= 0 || request.Quantity <= 0)
{
throw new ArgumentException("Invalid order details.");
}
return _repository.CreateAsync(request, cancellationToken);
}
}
Register the services and endpoint:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<IOrderRepository, OrderRepository>();
builder.Services.AddScoped<IOrderService, OrderService>();
var app = builder.Build();
app.MapPost("/orders", async (
CreateOrderRequest request,
IOrderService service,
CancellationToken cancellationToken) =>
{
try
{
var orderId = await service.CreateAsync(
request, cancellationToken);
return Results.Created(
$"/orders/{orderId}",
new { OrderId = orderId });
}
catch (ArgumentException ex)
{
return Results.BadRequest(new { Error = ex.Message });
}
});
app.Run();
The example illustrates the lifetime arrangement; a complete production order workflow would also require appropriate entity validation, authorization, error handling, transaction design, and any necessary stock or payment coordination.
Why are these services scoped?
- The request resolves
IOrderService. - The service uses
IOrderRepository. - The repository uses
AppDbContext. - All three can share the request's scope.
- The scope is disposed after request processing.
A singleton is not appropriate for this repository arrangement because it would capture a scoped dependency.
8.4 Production example: A background worker
A hosted service is generally registered as a singleton for the host's lifetime. It must not constructor-inject a scoped database context and retain it indefinitely.
Instead, create a scope for each unit of work:
public sealed class OrderCleanupWorker : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<OrderCleanupWorker> _logger;
public OrderCleanupWorker(
IServiceScopeFactory scopeFactory,
ILogger<OrderCleanupWorker> logger)
{
_scopeFactory = scopeFactory;
_logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
await using var scope =
_scopeFactory.CreateAsyncScope();
var cleanupService = scope.ServiceProvider
.GetRequiredService<IOrderCleanupService>();
await cleanupService.CleanupAsync(stoppingToken);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
_logger.LogError(
ex, "Order cleanup operation failed.");
}
await Task.Delay(
TimeSpan.FromMinutes(5), stoppingToken);
}
}
}
Register the worker and its dependencies:
builder.Services.AddScoped<IOrderCleanupService, OrderCleanupService>();
builder.Services.AddHostedService<OrderCleanupWorker>();
IOrderCleanupService can use scoped repositories and DbContext
instances. The explicit scope is disposed after each cleanup iteration.
In a complete worker, the retry strategy, delay behavior, shutdown handling, and error policy should be designed to suit the workload.
9. Folder Structure
For a small learning project:
ServiceLifetimeDemo/
├── Controllers/
│ └── LifetimeController.cs
├── Services/
│ ├── Interfaces/
│ │ ├── IProductService.cs
│ │ └── IOrderService.cs
│ ├── ProductService.cs
│ └── OrderService.cs
├── Data/
│ └── AppDbContext.cs
├── Models/
│ ├── Product.cs
│ └── Order.cs
├── Program.cs
└── appsettings.json
For a larger application, organize code by business feature or layer according to the architecture rather than creating folders for every minor type.
Service lifetimes are configured during composition, typically in
Program.cs or focused registration extension methods. Avoid scattering
inconsistent lifetime decisions across the codebase.
10. Execution Flow
Consider these registrations:
builder.Services.AddTransient<IEmailFormatter, EmailFormatter>();
builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddSingleton<IProductCache, ProductCache>();
When a request uses all three services:
- Application startup: ASP.NET Core records the service registrations.
- Request begins: The framework creates or establishes the request's DI scope.
- Transient resolution: The container creates an
EmailFormatterfor that resolution. - Scoped resolution: The container creates an
OrderServiceif it has not already been resolved in the request scope. - Singleton resolution: The container returns the registered
ProductCacheinstance, creating it if necessary. - Business logic runs: The endpoint or controller uses the resolved services.
- Response completes: ASP.NET Core completes request processing.
- Scope ends: Disposable services owned by the request scope are disposed.
- Singleton remains available: The singleton continues to be available to later requests until the container is disposed.
A new request repeats the process, but the singleton remains shared. Scoped and transient resolution behavior depends on how often each service is resolved.
11. Real Project Usage
Service lifetime selection is relevant across industries.
| Industry | Example | Typical lifetime choice | Reason |
|---|---|---|---|
| E-commerce | Order processing service | Scoped | Coordinates request-bound work and database access |
| E-commerce | Product cache | Singleton | Shares thread-safe cached data |
| Banking | Transfer processing service | Scoped | Keeps operations and dependencies bounded to a unit of work |
| Healthcare | Appointment repository | Scoped | Uses a scoped database context |
| Logistics | Address formatting helper | Transient | Performs lightweight transformations |
| Logistics | Background shipment processor | Hosted service with explicit scopes | Creates dependencies for each processing unit |
| Social media | Post repository | Scoped | Works with the current unit of work |
| Social media | Immutable application metadata | Singleton | Reuses data that does not need per-request state |
| Enterprise software | Report generation coordinator | Depends on workload | Lifetime depends on resource ownership and execution boundaries |
| Enterprise software | Configuration-based stateless helper | Transient or singleton | Depends on construction cost, dependencies, and thread safety |
These are typical choices, not universal rules. For example, a stateless service may be transient or singleton if all its dependencies support that lifetime and sharing is safe.
Banking transfer
A bank transfer involves validation, database operations, and audit records. A scoped transfer service can coordinate the request's work using scoped dependencies.
However, the lifetime alone does not guarantee financial correctness. Database transactions, concurrency controls, idempotency, authorization, and audit integrity must be designed separately.
Social media feed
A feed service might use scoped repositories to read user-specific data and a singleton cache abstraction to share reusable infrastructure. User-specific information must not be stored in shared singleton fields without proper isolation.
12. Performance Considerations
Memory
- Transient objects may increase allocation volume when resolved frequently.
- Scoped objects remain associated with their scope until disposal or release.
- Singletons can reduce repeated initialization but retain their reachable object graphs for longer.
A singleton is not automatically the most memory-efficient choice. A singleton that accumulates unbounded data can cause severe memory pressure.
CPU
Creating and initializing expensive objects repeatedly can consume CPU. Reusing a suitable singleton can reduce repeated work, while scoped services can avoid repeated construction within a request.
But object construction is only one part of performance. Database queries, serialization, network calls, and locking often matter more.
Scalability
A shared singleton with a lock around every operation may become a bottleneck. A poorly designed singleton can also produce contention between requests.
Scoped services can help isolate request-specific mutable state, but they do not guarantee that database access or the overall application is scalable.
Optimization guidelines
- Measure allocation and latency before changing lifetimes.
- Keep singleton state bounded.
- Use asynchronous I/O for supported I/O operations.
- Avoid expensive initialization on every transient resolution when reuse is appropriate.
- Dispose scopes and owned resources correctly.
- Never reuse a non-thread-safe dependency concurrently.
- Profile under realistic concurrent load.
- Consider distributed caching when data must be shared across multiple application instances.
13. Security Considerations
Cross-user data leakage
A singleton that stores the current user's ID, authorization result, or private response data in mutable fields can accidentally share information across requests.
Safer approach: Keep user-specific state in request-bound objects or explicit operation data. If using a cache, use suitable keys, access controls, and expiration.
Captive dependencies
A singleton that retains a scoped dependency may use a resource beyond its intended lifetime or reuse request-specific state incorrectly.
Safer approach: Use compatible lifetimes and explicit scopes for background work.
Resource exhaustion
A singleton that accumulates items indefinitely or a scope that retains large objects unnecessarily can increase memory use and reduce availability.
Safer approach: Apply bounded caches, expiration policies, disposal, and appropriate resource limits.
Thread-safety vulnerabilities
A singleton with unsynchronized mutable collections may produce inconsistent results or race conditions under concurrent requests.
Safer approach: Prefer immutable data, thread-safe collections, or carefully designed synchronization.
Sensitive logging
A singleton logger or telemetry component may process events from many users. Logging passwords, tokens, payment details, or health information is unsafe regardless of lifetime.
Safer approach: Use structured logging, redact sensitive fields, and enforce appropriate access and retention policies.
Security principle: Service lifetime is not an authorization mechanism. Every request still needs appropriate authentication, authorization, and data isolation.
14. Common Mistakes
Mistake 1: Registering every service as transient
Why it happens: Developers assume transient is the safest default because it creates fresh objects.
Problem: Expensive services may repeatedly initialize resources or allocate objects unnecessarily.
Fix: Choose the lifetime based on state, dependencies, resource ownership, and measured performance.
Mistake 2: Making every service a singleton
Why it happens: Developers want to avoid object creation.
Problem: Mutable state may be shared across concurrent requests, and scoped dependencies may be captured incorrectly.
Fix: Use singleton only when sharing is intentional and safe.
Mistake 3: Registering DbContext as singleton
Why it happens: Developers confuse sharing an instance with improving database performance.
Problem: EF Core DbContext is not thread-safe and is designed for
a bounded unit of work.
Fix: Use the normal scoped AddDbContext registration unless a
different, deliberately designed factory-based approach is appropriate.
Mistake 4: Injecting a scoped service into a singleton
Why it happens: The constructor compiles, so the lifetime relationship appears valid.
Problem: The singleton can retain the scoped instance beyond the scope in which it was intended to operate.
Fix: Change the service design or create an explicit scope for each operation.
Mistake 5: Assuming transient objects are immediately destroyed
Why it happens: Developers interpret "transient" as "temporary until the method finishes."
Problem: References and DI ownership may keep the object alive, and disposable transient objects resolved from a scope can be tracked until disposal.
Fix: Understand the object's ownership, references, and disposal path.
Mistake 6: Assuming scoped always means per HTTP request
Why it happens: Most web examples use request scopes.
Problem: Background workers and manually created scopes have different boundaries.
Fix: Think in terms of DI scopes, not HTTP requests alone.
Mistake 7: Storing user-specific state in a singleton
Why it happens: Developers use fields as a convenient way to share data.
Problem: One request may observe another request's data.
Fix: Pass user-specific data explicitly and keep shared services stateless where possible.
Mistake 8: Using a singleton with unsafe mutable collections
Why it happens: Developers assume the framework makes shared services thread-safe.
Problem: Concurrent access can cause race conditions or inconsistent data.
Fix: Prefer immutable state or use appropriate thread-safe data structures and synchronization.
Mistake 9: Building a second service provider during registration
Why it happens: Developers call BuildServiceProvider() to resolve
a dependency while configuring registrations.
Problem: It can create a second container with its own instances and ownership rules, potentially duplicating singletons.
Fix: Use DI factories, framework-supported options patterns, and normal constructor injection.
Mistake 10: Changing lifetimes just to silence validation errors
Why it happens: A developer changes a scoped service to singleton or makes all dependencies transient to eliminate an exception.
Problem: The application may run while violating intended resource and state boundaries.
Fix: Inspect the full dependency graph and choose compatible lifetimes. Enable scope validation during development.
15. Production Best Practices
- Choose lifetimes intentionally. Document why an important service uses its chosen lifetime.
- Use scoped
DbContextby default. Keep database work bounded to an appropriate unit of work. - Avoid scoped dependencies in singletons. Use explicit scopes where long-running services need scoped operations.
- Keep singletons stateless where practical. This simplifies concurrent use.
- Make shared mutable state thread-safe. Prefer immutable data when possible.
- Use transient for lightweight services. Avoid repeatedly constructing expensive objects without a reason.
- Understand disposal ownership. Know who creates, owns, and disposes each resource.
- Use
IServiceScopeFactoryfor background work. Create and dispose a scope around each independent operation. - Enable scope validation. Catch invalid scoped-to-singleton dependency relationships early.
- Avoid service locator patterns in business logic. Prefer constructor injection so dependencies are explicit.
- Do not build duplicate containers. Let the application's service provider manage registrations.
- Avoid unbounded singleton caches. Use expiration, capacity limits, and suitable eviction policies.
- Keep user state isolated. Never use a shared singleton field as implicit request storage.
- Avoid concurrent use of a single
DbContext. Use separate contexts or correctly bounded operations. - Measure before optimizing. Profile allocation, contention, latency, and throughput.
- Keep constructor work lightweight. Avoid blocking network calls or database queries during service creation.
- Pass cancellation tokens. Allow request and background operations to respond to cancellation.
- Use factories for special resource creation needs. For example,
EF Core provides
IDbContextFactory<TContext>when independently created contexts are appropriate. - Review the dependency graph. A service's effective resource lifetime depends on its dependencies and references.
- Do not confuse thread safety with lifetime. A transient service can still be used concurrently if a reference is shared; a singleton can be safe if designed appropriately.
- Avoid retaining
HttpContext. Do not store the current request context in singleton fields; access request-specific information through supported request-bound abstractions. - Use distributed infrastructure for cross-instance state. An in-memory singleton is local to its application container, not shared across all server instances.
- Treat lifetime changes as architectural changes. Review their effect on state, disposal, testing, and performance before deployment.
16. Interview Questions
Beginner Questions
1. What are service lifetimes in ASP.NET Core?
Service lifetimes define how the DI container creates and reuses service instances. The three built-in lifetimes are Transient (new instance per resolution), Scoped (one instance per scope), and Singleton (one shared instance per registration and container).
2. What is the difference between transient and scoped?
Transient services create new instances for each resolution. Scoped services reuse an instance within a scope. Resolving the same transient service twice normally gives different references, while resolving the same scoped service twice in the same scope gives the same reference.
3. What does AddSingleton() do?
It registers a service to be shared through the same DI container. The instance is generally created when first resolved for type- or factory-based registrations, then reused for subsequent resolutions. Singleton services must be designed for shared use and concurrent access.
4. Why is AddScoped() commonly used for repositories?
Repositories frequently use DbContext, which is scoped by default with
AddDbContext. Registering the repository as scoped allows it to share
the appropriate context within the current unit of work.
5. Can a transient service depend on a singleton?
Yes, provided the dependency is otherwise compatible. Each transient instance receives the shared singleton instance when resolved through the same container.
6. Can a singleton depend on a transient service?
Yes, but the singleton captures the transient instance injected into its constructor. That particular instance then lives as long as the singleton retains it. It does not receive a new transient instance for every operation automatically.
7. Which lifetime is suitable for DbContext?
Scoped is the standard choice with AddDbContext. It supports a bounded
unit of work and avoids sharing the same context concurrently across
unrelated requests.
8. What happens to scoped services after a request?
When the request scope ends, DI disposes the disposable services it owns in that scope. Non-disposable objects become eligible for garbage collection when no longer referenced.
9. Does singleton mean one instance across all servers?
No. It means one shared instance for the registration within a particular DI container. Separate application processes or server instances have separate containers and singleton instances.
10. How can you test whether two objects are the same instance?
Use ReferenceEquals(first, second). Resolve both services from the
same provider or scope when testing reuse semantics.
Intermediate Questions
11. What is a captive dependency?
A captive dependency occurs when a longer-lived service retains a shorter-lived dependency beyond the dependency's intended lifetime. A typical example is a singleton retaining a scoped repository or database context. Redesign the dependency relationship or create an explicit scope for each operation.
12. What is the difference between a service lifetime and a DI scope?
A lifetime is the registration's instance-management policy. A scope is the boundary within which scoped services are reused and disposed. A scoped lifetime uses the current scope, but a scope is not necessarily an HTTP request.
13. How do you inject a scoped service into a background worker?
Inject IServiceScopeFactory, create a scope when the worker needs to
perform a unit of work, resolve the scoped service from that scope, and
dispose the scope afterward.
14. Why should you avoid BuildServiceProvider() inside service registration?
It can create a second container with its own instances and ownership rules. This may duplicate singletons and lead to unexpected disposal behavior. Use supported registration factories and constructor injection instead.
15. Are transient services always thread-safe?
No. A transient service can still be shared through a reference, captured by a singleton, or used concurrently by multiple callers. Its lifetime alone does not guarantee thread safety.
16. Can two different scoped services share the same DbContext?
Yes, when they resolve the same registered context from the same scope. This is common when multiple request-bound services participate in one unit of work. They should not execute concurrent operations on that same context instance.
17. What does scope validation do?
Scope validation checks for invalid dependency relationships, such as a singleton depending directly on a scoped service. It can also help identify scoped services resolved from the root provider. Enable validation in development and tests.
18. Can a singleton depend on another singleton?
Yes. This is common when both services are designed for application-wide reuse. The dependency must still be safe for the singleton's lifetime and concurrent access.
19. What is the difference between AddSingleton<T>() and AddSingleton<T>(instance)?
The first form typically lets the container create the registered service instance when required. The second registers an existing instance supplied by the application. With a supplied instance, the application must consider ownership and disposal because it created the object outside the container.
20. What happens if a scoped service is resolved from the root provider?
With scope validation enabled, ASP.NET Core's DI container can throw an exception. Without validation, the service may effectively be retained in the root scope until the root provider is disposed, which is usually not intended. Resolve scoped services from a valid scope instead.
Advanced Questions
21. How do service lifetimes affect concurrent requests?
Transient and scoped registrations can reduce unintended sharing of instance state, but neither guarantees thread safety if references are shared or operations are concurrent. A singleton is shared, so mutable state must be safe under concurrent access. Consider the entire dependency graph.
22. Can a transient service be disposed before the request ends?
DI-owned disposable transient instances resolved from a scope are commonly tracked for disposal when that scope ends. They should not be assumed to be disposed immediately after their method returns. Manually created instances and resources explicitly disposed by application code have different ownership rules.
23. How does a singleton work in a multi-instance deployment?
Each application instance normally has its own DI container and singleton services. An in-memory cache is local to that instance. For shared cross-instance data, use a suitable shared infrastructure component, such as a distributed cache.
24. How would you handle a singleton service that needs a database context?
Do not retain a scoped DbContext in the singleton. Inject
IServiceScopeFactory to create an appropriate scope for each unit of
work, or use IDbContextFactory<TContext> when independently created
contexts suit the design. Dispose scopes or contexts according to their
ownership model.
25. What is the difference between IDisposable and IAsyncDisposable in DI?
IDisposable provides synchronous cleanup through Dispose().
IAsyncDisposable provides asynchronous cleanup through
DisposeAsync(). When asynchronous disposal is needed, use asynchronous
scope disposal where appropriate, such as await using with
CreateAsyncScope().
26. Why might a singleton introduce a memory leak?
A singleton remains reachable for the container's lifetime. If it accumulates unbounded entries, subscribes to events without unsubscribing, or retains large object graphs, those objects may remain in memory much longer than intended. Use bounded collections, correct event unsubscription, and suitable retention policies.
27. How would you investigate a service lifetime bug in production?
Reproduce the behavior and identify the service registration and dependency graph. Inspect instance IDs, scope creation and disposal, logs, memory usage, and concurrent access patterns. Add focused tests for expected lifetime semantics, then fix the ownership or lifetime design rather than merely changing the registration.
28. Can one implementation be registered with multiple lifetimes?
Yes, but each registration must be understood carefully.
builder.Services.AddSingleton<ProductService>();
builder.Services.AddTransient<IProductService>(sp =>
sp.GetRequiredService<ProductService>());
Here, the interface registration resolves the same singleton
ProductService. Despite AddTransient on the interface registration,
the underlying implementation is shared. This differs from independently
registering the implementation as transient.
29. How do you choose between a singleton and IMemoryCache?
IMemoryCache is a cache abstraction registered for application-level
use; its registered instance is typically shared. It provides cache
entries and expiration policies, whereas a custom singleton may simply
hold application state. Choose based on caching behavior, eviction,
expiration, and observability. Neither approach automatically
distributes data across server instances.
30. How do service lifetimes affect unit testing?
Tests can create independent scopes and verify reference equality, disposal, and dependency isolation. Singleton registrations can retain state between test operations if the same provider is reused, so tests should manage provider and scope lifetimes deliberately. Test both expected reuse and expected isolation.
17. Hands-on Exercise
Build a service lifetime diagnostic API
Objective: Create an ASP.NET Core API that shows how transient, scoped, and singleton services behave across multiple resolutions and HTTP requests.
Requirements
- Create an
IInstanceTrackerinterface with anInstanceIdproperty. - Implement three tracker classes.
- Register them using
AddTransient,AddScoped, andAddSingleton. - Create an endpoint at
/diagnostics/lifetimes. - Resolve each service twice within the same request.
- Return the IDs and
ReferenceEquals()results. - Call the endpoint repeatedly and observe which IDs change.
Expected observations
Test Expected result
Resolve transient twice in the same Different instances request
Resolve scoped twice in the same Same instance request
Resolve singleton twice in the same Same instance request
Compare scoped IDs across requests Different instances
Compare singleton IDs across Same instance for the same running requests container
Challenge: Add a disposable tracker that records when its
Dispose() method is called. Verify when the scoped instance is
disposed.
18. Mini Project: Service Lifetime Explorer
Build a small diagnostic dashboard for a .NET 9 Web API.
Features
- Display a unique ID for transient, scoped, and singleton services.
- Display whether repeated resolutions return the same reference.
- Show a request correlation ID.
- Log service construction and disposal.
- Include a scoped repository that demonstrates request-bound dependencies.
- Add a background worker that uses
IServiceScopeFactory. - Include tests for expected instance reuse.
- Enable dependency scope validation in development.
Suggested endpoints
| Endpoint | Purpose |
|---|---|
GET /api/lifetimes | Display current request's service instance IDs |
GET /api/lifetimes/resolve-twice | Compare repeated resolutions within one scope |
GET /api/lifetimes/history | Display bounded diagnostic events |
GET /api/health | Check basic application health |
Acceptance criteria
- Scoped services are isolated between requests.
- Singleton instances remain shared for the running container.
- Transient services return distinct instances for independent resolutions.
- No scoped dependency is retained by a singleton.
- Disposable scoped services are cleaned up when their scope ends.
- Diagnostic history is bounded to prevent unbounded memory growth.
- Automated tests verify lifetime semantics.
Extension: Run two application instances and compare singleton IDs. Explain why each instance has its own singleton even though both instances run the same code.
19. Quiz
Question 1
Which lifetime creates a new instance for each independent service resolution?
- A. Singleton
- B. Scoped
- C. Transient
- D. Root
Correct answer: C --- Transient.
Explanation: AddTransient instructs DI to create a new service
instance for each resolution. Existing references can still cause a
previously created object to remain alive.
Question 2
How many instances of a scoped service are normally shared by repeated resolutions in one HTTP request?
- A. One per resolution
- B. One per request scope
- C. One per application
- D. One per controller method
Correct answer: B --- One per request scope.
Explanation: The same scoped registration is reused within the same scope. Separate scopes receive separate instances.
Question 3
Which registration is generally appropriate for EF Core's DbContext?
- A.
AddSingleton - B.
AddScoped - C.
AddHostedService - D.
AddTransientin all cases
Correct answer: B --- AddScoped.
Explanation: AddDbContext uses a scoped lifetime by default,
providing a bounded unit of work. Special cases may use a context
factory, but a context should not be shared concurrently as a singleton.
Question 4
What happens if a singleton retains a scoped dependency?
- A. DI automatically creates a new dependency for every method call.
- B. The dependency always becomes transient.
- C. The shorter-lived dependency may be retained beyond its intended scope.
- D. The singleton becomes scoped.
Correct answer: C.
Explanation: The singleton can retain the scoped object in its constructor field. This can cause incorrect state reuse, resource-lifetime problems, or validation failures.
Question 5
Are singleton services automatically thread-safe?
- A. Yes
- B. No
- C. Only in development
- D. Only when registered by interface
Correct answer: B --- No.
Explanation: The DI container manages instance reuse, not synchronization of the service's internal state.
Question 6
Which service is generally suitable for a lightweight stateless formatting operation?
- A. Transient
- B. Singleton only
- C. Scoped only
- D. A new DI container per operation
Correct answer: A --- Transient.
Explanation: Transient is a reasonable choice for inexpensive, lightweight operations. A stateless formatter could also be singleton if its dependencies and implementation support safe sharing.
Question 7
A hosted service needs to use a scoped repository. What should it normally do?
- A. Change the repository to singleton
- B. Create a DI scope for the operation
- C. Store a request's
HttpContext - D. Build a second root provider
Correct answer: B --- Create a DI scope.
Explanation: A hosted service is long-lived. A manually created scope gives its scoped dependencies a valid, bounded lifetime.
Question 8
What does ReferenceEquals(first, second) test?
- A. Whether the objects contain equal values
- B. Whether the objects are the same reference
- C. Whether the objects are disposable
- D. Whether the objects are thread-safe
Correct answer: B.
Explanation: It checks reference identity, not whether two separate objects have equal property values.
Question 9
What is the main risk of storing user-specific mutable state in a singleton?
- A. The service becomes transient.
- B. The DI container stops working.
- C. Concurrent requests can share or expose unintended state.
- D. The object is immediately disposed.
Correct answer: C.
Explanation: A singleton is shared. User-specific state needs explicit isolation and must not accidentally leak between requests.
Question 10
What does a singleton mean in a multi-instance deployment?
- A. One object across all servers worldwide
- B. One object per HTTP request
- C. One shared instance for its registration within each DI container
- D. One object per database row
Correct answer: C.
Explanation: Each application process or host normally has its own DI container. Singleton instances are not automatically distributed between hosts.
20. Summary
One-minute revision
- Transient: A new instance per resolution.
- Scoped: One instance per DI scope.
- Singleton: One shared instance per registration and container.
AddTransient,AddScoped, andAddSingletonregister the respective lifetimes.DbContextis scoped by default withAddDbContext.- Singletons need careful concurrency and state management.
- Long-running workers should create scopes for scoped work.
- Service lifetime determines DI reuse, not authorization or automatic thread safety.
Five-minute revision
Start by understanding the object graph. A controller depends on a service, which may depend on a repository, which may depend on a database context. Every dependency must be compatible with the lifetime of the service that retains it.
Transient is useful for lightweight operations and fresh instances. Scoped is appropriate for request-bound work and many data-access services. Singleton is suitable for safely shared, long-lived components.
Next, understand scope disposal. A scoped service belongs to its scope; a singleton belongs to the container's lifetime. Disposable objects are cleaned up according to ownership, not simply because a method returned.
Finally, remember that lifetime decisions affect correctness as much as performance. Avoid captive dependencies, unsafe shared state, unbounded caches, and concurrent use of a non-thread-safe database context.
Bullet-point summary
- DI manages service construction and reuse.
- Lifetime registrations are applied per service registration.
- A new transient instance does not imply immediate disposal.
- Scoped services are reused within a scope.
- Singletons are shared within a container.
- Singleton state can be accessed concurrently.
- Background services should create scopes for scoped operations.
AddDbContextnormally registers a scoped context.- Scope validation helps detect lifetime misuse.
- Separate application containers have separate singleton instances.
Memory tricks
- Transient = Turnover: New instance for each resolution.
- Scoped = Same scope: Shared within one scope, separate across scopes.
- Singleton = Shared: One instance for the registration within its container's lifetime.
Flashcards
| Question | Answer |
|---|---|
What does AddTransient do? | Creates a new service instance for each resolution. |
What does AddScoped do? | Reuses one instance of the registration within the current DI scope. |
What does AddSingleton do? | Shares one instance for that registration within the DI container. |
Why is DbContext normally scoped? | It represents a bounded unit of work and is not thread-safe. |
| What is a captive dependency? | A shorter-lived dependency retained by a longer-lived service beyond its intended scope. |
| How should a background worker use scoped services? | Create and dispose a DI scope for each unit of work. |
21. Cheat Sheet
| Need | Registration or technique |
|---|---|
| Fresh lightweight instance | AddTransient<TService, TImpl>() |
| Reuse within a scope | AddScoped<TService, TImpl>() |
| Share instance within a container | AddSingleton<TService, TImpl>() |
| Database context | AddDbContext<TContext>() |
| Scoped work in a hosted service | IServiceScopeFactory |
| Create a scope | CreateScope() |
| Create an async-disposable scope | CreateAsyncScope() |
| Resolve a required service | GetRequiredService<T>() |
| Compare reference identity | ReferenceEquals(a, b) |
| Supply a factory | AddSingleton<T>(sp => ...) |
| Inspect dependency relationships | Enable DI scope validation |
| Share cache across application instances | Use suitable distributed caching infrastructure |
Remember: Transient means new resolution, scoped means same scope, and singleton means shared container instance.
22. Comparison Table
Service lifetimes versus related concepts
| Concept | Purpose | Difference |
|---|---|---|
| Service lifetime | Controls instance reuse through DI | Transient, scoped, singleton |
| DI scope | Defines a boundary for scoped services | May represent a request or a manually created unit of work |
| Garbage collection | Reclaims managed memory for unreachable objects | Does not itself define DI service reuse |
IDisposable | Synchronous resource cleanup | Does not determine service lifetime |
IAsyncDisposable | Asynchronous resource cleanup | Does not determine service lifetime |
| Thread safety | Ensures correctness under concurrent access | Not guaranteed by any service lifetime |
IDbContextFactory<T> | Creates independent EF Core contexts | Useful when contexts need separate ownership boundaries |
IMemoryCache | Provides in-process caching functionality | Typically shared, but not distributed across application instances |
| Distributed cache | Shares cached data through external infrastructure | Can support multiple application instances |
IHttpContextAccessor | Provides access to the current HTTP context where applicable | Does not make request data safe to retain in a singleton field |
Transient versus scoped versus singleton
| Decision factor | Transient | Scoped | Singleton |
|---|---|---|---|
| New instance for each resolution | Yes | No, within the same scope | No, within the same container registration |
| Reused across requests | Only if retained or shared through references | No, not across normal request scopes | Yes |
| Suitable for request-specific state | Only with careful instance ownership | Often suitable | Generally unsuitable in mutable instance fields |
| Typical disposal boundary for DI-created disposable objects | Owning scope/container | Scope | Container |
| Primary concern | Allocation and dependency ownership | Scope boundaries | Shared state and concurrency |
23. Key Takeaways
- Service lifetimes control instance reuse through the DI container.
- Transient, scoped, and singleton have different reuse boundaries.
- Scoped services are not necessarily HTTP-request-scoped; the DI scope defines the boundary.
- A longer-lived service must not accidentally retain a dependency beyond that dependency's intended lifetime.
- A singleton's mutable state must be designed for concurrent access.
- EF Core
DbContextis normally scoped and must not be shared across concurrent operations. - Background services need explicit scopes when performing scoped work.
- Object ownership and disposal matter as much as the registration itself.
- In-memory singletons are local to their DI container, not automatically distributed.
- Select lifetimes based on correctness, ownership, dependencies, and measured performance.
24. Revision Checklist
- Explain the purpose of service lifetimes.
- Differentiate transient, scoped, and singleton.
- Use
AddTransient,AddScoped, andAddSingletoncorrectly. - Explain why repeated scoped resolutions share an instance.
- Explain why a singleton is shared across requests.
- Describe how DI scopes are created and disposed.
- Explain why
DbContextis normally scoped. - Identify a captive dependency.
- Use
IServiceScopeFactoryin a background worker. - Explain why singleton services require safe concurrent behavior.
- Describe the ownership of disposable services.
- Test instance identity using
ReferenceEquals(). - Explain why a singleton is not shared across independent application containers.
- Enable scope validation and diagnose lifetime errors.
- Choose service lifetimes based on dependencies and resource ownership.
25. Further Reading
Continue learning through these related Logic Lense Roadmaps modules:
- Dependency Injection in ASP.NET Core --- Understand service registration, constructor injection, and the DI container.
- Configuration & appsettings.json --- Learn how ASP.NET Core loads configuration and how services consume options.
- Middleware in ASP.NET Core --- Understand the HTTP request pipeline and middleware execution.
- Options Pattern in ASP.NET Core --- Learn how to bind and validate strongly typed configuration.
- Entity Framework Core Fundamentals --- Understand database contexts, queries, tracking, and units of work.
- Hosted Services and Background Tasks --- Learn how long-running workers operate outside ordinary HTTP requests.
- Caching in ASP.NET Core --- Explore in-memory and distributed caching strategies.
- SOLID Principles in C# --- Understand how dependency inversion and separation of responsibilities influence service design.
These modules build on the fundamentals covered here and prepare you to make more informed architectural decisions in real ASP.NET Core applications.
Last updated 10/13/2026
Your notes
Sign in to save personal notes on this topic — they'll sync across your devices.
Was this tutorial helpful?
Help us create more free learning resources. Learn more
