In ASP.NET Core, if a controller and its service both inject the same AddScoped and AddTransient types, how many instances does one request create?
answer
- one scope per HTTP request
- transient: one per injection point
- scoped: shared inside the scope
- RequestServices scope created lazily
- disposed when the response completes
basics
~10 sOne scoped instance, shared by the controller and the service, and two transient instances, one per injection point. The request's scope disposes both kinds when the response completes; a singleton stays one instance app-wide.
solid answer
~40 sASP.NET Core opens one DI scope per HTTP request. An `AddScoped` type is created once in that scope, so the controller and the service it uses receive the same object; an `AddTransient` type is created at every injection point, so the same request gets two. A concurrent request has its own scope and therefore its own scoped instance, while an `AddSingleton` type is one object for the whole application, created the first time something resolves it. When the response completes, the request scope is disposed and every `IDisposable` or `IAsyncDisposable` scoped or transient object it created is disposed with it, newest first. Singletons are disposed only when the host shuts down.
code
csharp · 14 linesbuilder.Services.AddSingleton<IQuoteFeed, QuoteFeed>();
builder.Services.AddScoped<IWatchlistService, WatchlistService>();
builder.Services.AddTransient<IPriceFormatter, PriceFormatter>();
// One request to WatchlistController:
// QuoteFeed -> the single app-wide instance
// WatchlistService -> 1 instance, shared by controller and filters
// PriceFormatter -> 2 instances (controller + WatchlistService)
public class WatchlistService(IPriceFormatter formatter) : IWatchlistService { }
public class WatchlistController(
IWatchlistService watchlist,
IPriceFormatter formatter,
IQuoteFeed feed) : ControllerBase { }go deeper
Recall the counts: one scoped instance per request, one transient per injection point, one singleton per app. Say who disposes them and when.
Explain that the request scope comes from IServiceScopeFactory, is created lazily and disposed after the response, and that disposal runs in reverse creation order.
Show judgment about lifetime choice: disposable or expensive transients resolved often, scoped state that must not leak across requests, and singletons that must be thread-safe.
Frame lifetime defaults as a team convention: which lifetimes reviewers accept by default, and how scope validation and tests keep a large codebase from drifting into captive dependencies.
## The three registration methods ASP.NET Core's built-in container (`Microsoft.Extensions.DependencyInjection`) records a **lifetime** for every registration on `builder.Services`. The lifetime decides how many objects the container builds and how long it keeps them: | Registration | Instances | Created | Disposed | |---|---|---|---| | `AddSingleton<IQuoteFeed, QuoteFeed>()` | one per application | on first resolution | when the host shuts down | | `AddScoped<IWatchlistService, WatchlistService>()` | one per scope (one per HTTP request) | on first resolution in that scope | when the scope ends | | `AddTransient<IPriceFormatter, PriceFormatter>()` | one per resolution | every time it is injected or requested | when the scope that created it ends | A **scope** is a container boundary created with `IServiceScopeFactory`. ASP.NET Core creates one for each request, lazily: the first time anything reads `HttpContext.RequestServices` (at the latest when your endpoint's dependencies are resolved), the framework calls `CreateScope()` and registers the scope with `Response.RegisterForDisposeAsync`, so it is disposed after the response completes. ## Counting instances in one request Take a stock-trading dashboard with this wiring: ```csharp builder.Services.AddScoped<IWatchlistService, WatchlistService>(); builder.Services.AddTransient<IPriceFormatter, PriceFormatter>(); public class WatchlistService(IPriceFormatter formatter) : IWatchlistService { } public class WatchlistController( IWatchlistService watchlist, // scoped IPriceFormatter formatter) // transient : ControllerBase { } ``` When a request reaches `WatchlistController`: - `IWatchlistService` is resolved once in the request scope. If a filter, a second service or the handler asks for it again in the same request, they all get **the same object**. - `IPriceFormatter` is resolved twice: once for the controller's constructor and once for `WatchlistService`'s constructor. That is **two objects**. - A second request running at the same moment has its own scope, so it gets its own `WatchlistService` and its own formatters. Scoped never means "per user" or "per session": nothing scoped survives into the next request. A quick way to prove it is to give each class a `Guid Id { get; } = Guid.NewGuid();` and log the ids; the scoped ids match within a request and differ across requests, while the transient ids differ everywhere. ## Disposal at the end of the request The container disposes what **it** created. It tracks every disposable scoped or transient object in the scope that resolved it, and when the scope is disposed: 1. It walks that list in **reverse order of creation**, so a service is disposed before the dependencies it was built from. 2. It calls `DisposeAsync` on `IAsyncDisposable` objects (the request scope is disposed asynchronously) and `Dispose` on the rest. 3. After that, the scope refuses further resolutions with an `ObjectDisposedException`. So you never wrap an injected service in a `using` block: disposing it yourself leaves the container holding a dead object that other consumers in the same request may still use, and the container will dispose it again anyway. Singletons live in the **root** scope (`app.Services`), which is disposed only when the host stops. A transient resolved from the root rather than from a request scope is therefore kept until shutdown, which is why per-request work should always run inside a scope. ## Choosing a lifetime for a web app - **Singleton** for thread-safe, stateless or shared-state services: a quote feed client, a cache, configuration readers. Everything a singleton holds lives for the life of the app, so it must not hold a shorter-lived service. - **Scoped** for anything tied to one unit of work: a `DbContext`, a repository, a service that carries the current request's user or correlation data. - **Transient** for lightweight, stateless helpers where sharing buys nothing. Avoid transient for expensive or disposable types that are resolved often, because every resolution allocates and the scope holds each disposable until it ends. ## What interviewers listen for - The number per request, not just "short-lived": scoped is one per request, transient is one per injection. - That two concurrent requests never share a scoped instance. - That disposal is the container's job and happens when the scope ends, not when the consumer is done with the object. - That singletons are created lazily, on first resolution, unless you register a ready-made instance. The same rules hold whether the endpoint is a controller action, a Razor Page or a Minimal API handler: all of them resolve from the request scope.
- When is the request scope created, and when is it disposed?It is created lazily the first time `HttpContext.RequestServices` is read, at the latest when the endpoint's dependencies are resolved, and it is registered with `Response.RegisterForDisposeAsync`. After the response completes, the scope's `DisposeAsync` runs and disposes every disposable scoped and transient object it created, newest first.
- Is a singleton created when builder.Build() runs?No. A singleton registered by type or factory is built the first time something resolves it, then cached in the root scope. Only a singleton registered as a ready-made instance, as in `AddSingleton<IQuoteFeed>(new QuoteFeed())`, exists before the app starts, and the container does not dispose that one.
A scoped service is a tray handed to one restaurant table: everyone at that table shares it, and staff clear it when the guests leave. A transient is a fresh napkin for every person who asks, and a singleton is the kitchen everyone shares.
- A scoped service lives for the user's session and keeps state between requests.
- AddTransient gives one instance per request, shared by everyone in it.
- Scoped means one instance per thread handling the request.
- You should wrap injected services in a using block to dispose them.
- Every singleton is instantiated eagerly when builder.Build() runs.