Covers the three built-in service lifetimes, how the container caches instances for each, what creates and disposes a scope in ASP.NET Core, and why worker services have no scope unless you create one.
The lifetime tells the container how long to reuse an instance:
HttpContext.RequestServices) and disposes it when the response finishes, so a DbContext is shared by everything in one request.A worker service has no requests, so there is no scope unless you create one with IServiceScopeFactory.CreateAsyncScope() per message or per loop iteration. The rule that ties it together: a service may only depend on services that live at least as long as it does.
"A lifetime is the container's caching rule. A singleton is created once, the first time someone asks for it, cached in the root provider and disposed when the host shuts down. A scoped service is cached per scope: ask twice inside the same scope and you get the same object, ask in another scope and you get a new one. A transient is never cached: every constructor parameter that asks for it gets a fresh instance.
A scope is just an
IServiceScopewith its ownServiceProviderand its own list of things to dispose. In ASP.NET Core the hosting layer creates one at the start of every request and puts it onHttpContext.RequestServices; controllers, Minimal API handlers and anything they depend on are resolved from it, and when the request ends the scope is disposed along with every scoped and transient disposable it created. That's whyAddDbContextregisters the context as scoped: one unit of work per request.In a worker service there's no request, so nothing creates a scope for you.
BackgroundServiceitself is a singleton. If it needs aDbContext, I injectIServiceScopeFactoryand create a scope per message or per iteration, so each unit of work gets fresh scoped services that are disposed when it finishes. The mistake I see is resolving scoped services from the root provider: they never get disposed and quietly become singletons. Lifetime is about who owns the instance and when it dies, not just how many you get."
| Lifetime | Instances | Created | Disposed | Typical use |
|---|---|---|---|---|
| Singleton | 1 per root provider | First resolve (or you pass an instance) | Host shutdown, if the container created it | Caches, IHttpClientFactory, configuration-derived services, stateless thread-safe services |
| Scoped | 1 per scope | First resolve in that scope | Scope disposal | DbContext, unit of work, per-request user context |
| Transient | 1 per resolve | Every resolve | Disposal of the scope that resolved it | Lightweight stateless services, builders |
| Host | Who creates scopes | Scope boundary |
|---|---|---|
| ASP.NET Core (MVC, Minimal APIs) | The framework, per request | One HTTP request |
| SignalR hub | The framework, per hub method call | One hub invocation |
| Blazor Server | The framework, per circuit | The user's connection (can be hours) |
Worker service / BackgroundService |
You, via IServiceScopeFactory |
Whatever you choose: one message, one batch |
| Console app / tests | You | Whatever you choose |
| Consumer β dependency | OK? |
|---|---|
| Transient β anything | Yes (the transient lives no longer than its consumer's scope) |
| Scoped β scoped / singleton | Yes |
| Singleton β singleton | Yes |
| Singleton β scoped or transient-disposable | No: captive dependency |
In an order API, OrdersDbContext is scoped, so the handler, the repository and the outbox writer in one request share one change tracker and commit in one SaveChangesAsync. The same code in a queue worker created one scope per message; before that fix, a single context lived for the process lifetime, its change tracker grew to [hundreds of thousands of] entities and memory climbed until the pod restarted.
Checks that the candidate knows what each lifetime caches, what a scope actually is, and that worker services need explicit scopes.
Green flags
IServiceScope" and says ASP.NET Core creates one per requestBackgroundService is a singleton and needs IServiceScopeFactoryRed flags
DbContext straight into a hosted serviceServiceCollection is just a list of ServiceDescriptors: service type, implementation (type, factory or instance) and ServiceLifetime. BuildServiceProvider() turns that into a root ServiceProvider that owns:
ServiceProviderEngineScope) with its own disposables list.Every CreateScope() makes a new engine scope with an empty scoped cache and its own disposables list.
Root ServiceProvider
ββ singleton cache (shared by every scope)
ββ root scope disposables
ββ CreateScope() ββ¬β Scope A: scoped cache, disposables
ββ Scope B: scoped cache, disposables
IDisposable or IAsyncDisposable, add it to the current scope's disposables list.That last point is why a transient disposable resolved from the root lives until the app stops.
Kestrel accepts request
β HttpContext created
β RequestServices = scopeFactory.CreateAsyncScope().ServiceProvider
β middleware β routing β endpoint (controller / handler resolved here)
β response completes
β scope.DisposeAsync(): scoped + transient disposables, reverse creation order
AddHostedService<T>() registers the hosted service as a singleton. Its constructor runs once, from the root provider. Anything scoped must come from a scope you create:
ExecuteAsync loop
ββ for each message:
await using scope = scopeFactory.CreateAsyncScope();
handler = scope.ServiceProvider.GetRequiredService<IHandler>();
await handler.HandleAsync(msg, ct);
(scope disposed β DbContext disposed)
With ValidateScopes = true (on by default when the environment is Development), the provider throws if a scoped service is resolved from the root, or if a singleton depends on a scoped service. Production defaults to off, so the bug ships silently unless you enable it everywhere.
Guid Id = Guid.NewGuid(), one per lifetime. Resolve each twice in two scopes and print the ids.IDisposable and log in Dispose. Resolve it from the root and from a scope; see which one disposes when.app.Services with ValidateScopes on and read the exception message.BackgroundService that injects a scoped service directly and watch it fail at start-up in Development.A console demo that prints instance ids per lifetime and shows when disposal happens.
using Microsoft.Extensions.DependencyInjection;
namespace LifetimeDemo;
public abstract class Tracked : IDisposable
{
public Guid Id { get; } = Guid.NewGuid();
public void Dispose() => Console.WriteLine($" disposed {GetType().Name} {Id.ToString()[..8]}");
}
public sealed class SingletonService : Tracked;
public sealed class ScopedService : Tracked;
public sealed class TransientService : Tracked;
public static class Program
{
public static void Main()
{
var services = new ServiceCollection()
.AddSingleton<SingletonService>()
.AddScoped<ScopedService>()
.AddTransient<TransientService>();
// ValidateScopes catches scoped-from-root and singletonβscoped at resolve time.
using var root = services.BuildServiceProvider(new ServiceProviderOptions
{
ValidateScopes = true,
ValidateOnBuild = true
});
for (var i = 1; i <= 2; i++)
{
Console.WriteLine($"Scope {i}");
using var scope = root.CreateScope();
var sp = scope.ServiceProvider;
Console.WriteLine($" singleton same? {ReferenceEquals(sp.GetRequiredService<SingletonService>(), sp.GetRequiredService<SingletonService>())}"); // True
Console.WriteLine($" scoped same? {ReferenceEquals(sp.GetRequiredService<ScopedService>(), sp.GetRequiredService<ScopedService>())}"); // True (new per scope)
Console.WriteLine($" transient same? {ReferenceEquals(sp.GetRequiredService<TransientService>(), sp.GetRequiredService<TransientService>())}"); // False
} // scoped + both transients disposed here, reverse creation order
Console.WriteLine("Root disposing");
} // singleton disposed here
}
The worker-service shape: a scope per unit of work.
namespace Orders.Worker;
public interface IOrderProcessor
{
Task<int> ProcessPendingAsync(CancellationToken ct);
}
public sealed class OrderWorker(IServiceScopeFactory scopes, ILogger<OrderWorker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(10));
while (await timer.WaitForNextTickAsync(stoppingToken))
{
// New scope = new DbContext, disposed at the end of the iteration.
await using var scope = scopes.CreateAsyncScope();
var processor = scope.ServiceProvider.GetRequiredService<IOrderProcessor>();
var count = await processor.ProcessPendingAsync(stoppingToken);
logger.LogInformation("Processed {Count} orders", count);
}
}
}
CreateScope() brackets; in ASP.NET Core that is one request, regardless of threads or users. Instead: Describe it as "one instance per IServiceScope" and name who creates the scope.DbContext) into a BackgroundService constructor. Why it is wrong: The hosted service is a singleton, so the scoped service is resolved from the root and lives for ever; Development throws, Production silently shares one context. Instead: Inject IServiceScopeFactory and create a scope per unit of work.ExecuteAsync and looping inside it. Why it is wrong: The scope lives as long as the worker, so its DbContext and transient disposables accumulate exactly as if they were singletons. Instead: One scope per message, batch or timer tick.IDisposables are tracked by the scope that resolved them; resolved from the root they are held until shutdown. Instead: Resolve disposable transients inside a scope, or use a factory you dispose yourself.AddSingleton(instance). Why it is wrong: The container only disposes what it created. Instead: Dispose pre-built instances yourself or register a factory.ObjectDisposedException or reads stale state. Instead: Store data (ids, DTOs), never services.app.Services at start-up without a scope. Why it is wrong: That is the root provider; scoped services throw in Development and leak elsewhere. Instead: using var scope = app.Services.CreateScope(); for start-up work.The lifetime is really an ownership contract: who creates the object, who is allowed to share it, and who disposes it. Most production DI bugs are a mismatch between that contract and reality: a singleton holding a scoped DbContext, a transient disposable owned by the root, a worker that never creates a scope. When I review registrations I ask two questions per service: is it safe to share across threads, and does it hold something that must be released per unit of work?
| Lifetime | When it fits | Cost | When not to |
|---|---|---|---|
| Singleton | Stateless or thread-safe shared state, expensive to build | Must be thread-safe; can't take scoped deps | Holds per-request data or a DbContext |
| Scoped | Per-unit-of-work state, DbContext |
Needs a scope; meaningless in a root-only console app | Used from singletons without a scope |
| Transient | Lightweight, stateless, or needs a fresh instance per consumer | Allocation per resolve; disposables tracked by scope | Expensive to construct, or disposable resolved from root |
I turn on ValidateScopes and ValidateOnBuild in every environment, so lifetime mistakes fail at start-up in CI rather than as memory growth in production.
IServiceCollection is just a list of ServiceDescriptors: a service type, an implementation (type, instance or factory delegate) and a lifetime. AddSingleton, AddScoped and AddTransient append to that list.
T gives you the last registration, while injecting IEnumerable<T> gives you all of them in registration order.TryAdd* adds only if nothing is registered for that service type, which is how libraries provide overridable defaults. TryAddEnumerable adds only if that exact implementation isn't already there.Replace swaps the first registration; RemoveAll clears them.The trade-off: ordering makes overrides easy but silent, so registration order bugs are easy to write and hard to see.
A captive dependency is a shorter-lived service captured by a longer-lived one, usually a scoped DbContext held by a singleton. The scoped instance stops being per-request: in production it is shared across threads (EF's "second operation" exceptions), serves stale data from its identity map, keeps growing its change tracker and is never disposed.
ValidateScopes = true makes the provider throw when a singleton's graph contains a scoped service or a scoped service is resolved from the root. The host enables it only in Development by default; turn it on everywhere with builder.Host.UseDefaultServiceProvider(o => { o.ValidateScopes = true; o.ValidateOnBuild = true; }). The cost is a small check on resolution and a one-off graph walk at start-up, far cheaper than the outage. Fix by aligning lifetimes, or creating per-operation instances with IDbContextFactory<T> or IServiceScopeFactory.
The composition root is the single place where the application's object graph is wired up: in ASP.NET Core, Program.cs and the AddXxx() extension methods it calls. It is the only code that knows about concrete implementations and the container.
Everything else asks for what it needs through its constructor. If business classes call IServiceProvider.GetService themselves, that is the service locator anti-pattern: their dependencies are hidden from the signature, a missing registration only shows up at run time, and unit tests need a container instead of a couple of fakes. Keeping resolution in the root keeps business code independent of the container, easier to test and easier to maintain. Framework-driven resolution (middleware Invoke parameters, [FromServices], Minimal API parameters) is fine because it is infrastructure acting on your behalf.
Last updated 23 Nov 2026.