skip to content

IServiceCollection Wiring

Registering services on IServiceCollection and resolving them per request: lifetimes and scopes, TryAdd and keyed services, Scrutor scanning. Interviewers lead with the captive dependency bug.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

14

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?

level: juniorimportance: must knowfreq 82%

answer

  1. one scope per HTTP request
  2. transient: one per injection point
  3. scoped: shared inside the scope
  4. RequestServices scope created lazily
  5. disposed when the response completes

basics

~10 s

One 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 s

ASP.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 lines
csharp
builder.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

for a junior

Recall the counts: one scoped instance per request, one transient per injection point, one singleton per app. Say who disposes them and when.

for a middle

Explain that the request scope comes from IServiceScopeFactory, is created lazily and disposed after the response, and that disposal runs in reverse creation order.

for a senior

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.

for a principal

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.
open as a page

In ASP.NET Core, when IPaymentGateway is registered twice with AddScoped, what does constructor injection receive, and what does IEnumerable<IPaymentGateway> receive?

level: juniorimportance: must knowfreq 62%

basics

~10 s

Constructor injection of IPaymentGateway gets the implementation from the last AddScoped call; IEnumerable<IPaymentGateway> gets one instance of every unkeyed registration, in registration order. The container raises no error about the duplicate.

open as a page

In ASP.NET Core 10, what goes wrong when a singleton price cache takes a scoped DbContext in its constructor, and how do you fix it?

level: middleimportance: must knowfreq 72%

basics

~20 s

It is a captive dependency: the singleton keeps one DbContext for the app's lifetime. Development fails at builder.Build() with "Cannot consume scoped service"; Production starts and shares that context across concurrent requests. Create a scope per refresh with IServiceScopeFactory.

open as a page

In ASP.NET Core 10, how do you choose among three keyed IPaymentGateway registrations per request, and what can go wrong with the key?

level: middleimportance: must knowfreq 54%

basics

~10 s

Register each gateway with AddKeyedScoped<IPaymentGateway, T>(key), then resolve at runtime with GetRequiredKeyedService<IPaymentGateway>(order.Provider) from the request's IServiceProvider. Keys match by Equals, so case or type mismatches throw InvalidOperationException.

open as a page

In ASP.NET Core 10, how do you replace the built-in container through IServiceProviderFactory, and what do you lose or gain by doing it?

level: seniorimportance: must knowfreq 45%

basics

~10 s

Pass an IServiceProviderFactory<TContainerBuilder> to builder.Host.UseServiceProviderFactory and add container-specific registrations in builder.Host.ConfigureContainer<TContainerBuilder>. You gain the container's extra features but lose the default factory's Development scope validation.

open as a page

With Scrutor in ASP.NET Core, what does each step of services.Scan(s => s.FromAssemblyOf<GetShipmentHandler>().AddClasses(...).AsImplementedInterfaces().WithScopedLifetime()) do?

level: juniorimportance: should knowfreq 36%

basics

~10 s

Scan reflects over the assembly containing GetShipmentHandler, AddClasses picks its public non-abstract classes (optionally filtered), AsImplementedInterfaces registers each class under every interface it implements, and WithScopedLifetime makes those registrations scoped.

open as a page

With Scrutor 7 in ASP.NET Core, which Scan defaults surprise teams (lifetime, visibility, duplicates and interfaces), and how do you override each?

level: middleimportance: should knowfreq 28%

basics

~10 s

Without a lifetime call Scrutor registers transient; AddClasses() skips internal classes; the default RegistrationStrategy.Append duplicates anything already registered; and AsImplementedInterfaces registers every interface, IDisposable included. Override with With*Lifetime, publicOnly: false, UsingRegistrationStrategy and a predicate.

open as a page

In ASP.NET Core, how do you use scoped services outside an HTTP request with IServiceScopeFactory, and why prefer CreateAsyncScope over CreateScope?

level: middleimportance: should knowfreq 55%

basics

~10 s

Inject IServiceScopeFactory, open await using var scope = factory.CreateAsyncScope(), and resolve from scope.ServiceProvider. CreateAsyncScope's AsyncServiceScope disposes IAsyncDisposable services properly; a plain Dispose() throws when a scoped service implements only IAsyncDisposable.

open as a page

In ASP.NET Core 10, what do ServiceProviderOptions.ValidateScopes and ValidateOnBuild each check, and why might a captive dependency still reach production?

level: middleimportance: should knowfreq 46%

basics

~10 s

ValidateScopes rejects scoped services resolved from the root provider or captured by singletons; ValidateOnBuild checks every registration at builder.Build(). WebApplicationBuilder enables both only in Development, and factory lambdas escape the build-time check.

open as a page

In ASP.NET Core, how do you register IRepository<T> once for every entity with an open generic, and when does a closed registration take over?

level: middleimportance: should knowfreq 42%

basics

~10 s

Register services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>)); the container closes EfRepository<T> for each requested T. A closed registration such as IRepository<Order> wins for that type regardless of order, because exact matches are tried first.

open as a page

In ASP.NET Core, how do TryAddScoped, TryAddEnumerable, Replace and RemoveAll differ from a plain AddScoped, and why do library AddX methods use them?

level: middleimportance: should knowfreq 44%

basics

~20 s

TryAddScoped adds only when the service type has no registration yet; TryAddEnumerable skips only an identical implementation type; Replace swaps the first matching registration; RemoveAll deletes every unkeyed one. Libraries use TryAdd so app registrations survive and AddX stays idempotent.

open as a page

With Scrutor, how does services.Decorate(typeof(IQueryHandler<,>), typeof(CachingQueryHandler<,>)) wrap forty scanned handlers, and what makes it throw or skip registrations?

level: seniorimportance: should knowfreq 33%

basics

~20 s

Decorate walks the descriptors registered so far, re-registers each matching handler under a generated key and replaces it with a factory that builds CachingQueryHandler around it, keeping its lifetime. It throws DecorationException when nothing matches; open generic registrations are skipped.

open as a page

In ASP.NET Core, why does resolving IDisposable transient services from app.Services grow memory, and which instances does the container never dispose?

level: seniorimportance: should knowfreq 34%

basics

~20 s

The container tracks every disposable it builds in the resolving scope; the root scope behind app.Services lasts until shutdown, so root-resolved disposable transients pile up. Instances you pass in, as in AddSingleton(new X()), are never disposed by the container.

open as a page

In ASP.NET Core, when does a registration need a factory lambda or ActivatorUtilities.CreateInstance instead of a type mapping, and what does each cost?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Use a factory lambda when construction needs runtime values, configuration-driven choice or forwarding; use ActivatorUtilities.CreateInstance inside it to pass the extra values while the container fills the remaining parameters. The cost: hand-written construction the container cannot validate or inspect.

open as a page