skip to content

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%

answer

  1. no request, no request scope
  2. IServiceScopeFactory is a singleton
  3. AsyncServiceScope with await using
  4. IAsyncDisposable-only service breaks Dispose()
  5. never let resolved services escape

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.

solid answer

~40 s

Outside a request there is no request scope, so code such as a singleton's timer refresh, startup work or a fire-and-forget task must create its own. Inject `IServiceScopeFactory`, a singleton that scope validation explicitly allows inside singletons, then write `await using var scope = scopes.CreateAsyncScope();` and resolve everything from `scope.ServiceProvider`. All services resolved there share that scope and are disposed when it ends. `CreateAsyncScope` returns an `AsyncServiceScope` struct that implements `IAsyncDisposable`, so disposal awaits `DisposeAsync` on services that need it; calling synchronous `Dispose()` on a scope holding a service that implements only `IAsyncDisposable` throws `InvalidOperationException` ("... type only implements IAsyncDisposable. Use DisposeAsync to dispose the container."). Never let a resolved service outlive its scope.

code

csharp · 12 lines
csharp
app.MapPost("/orders", (OrderRequest req, IServiceScopeFactory scopes) =>
{
    _ = Task.Run(async () =>
    {
        // The request scope is gone by now: open a scope for this work.
        await using var scope = scopes.CreateAsyncScope();
        var db = scope.ServiceProvider.GetRequiredService<TradingDbContext>();
        db.TradeAudits.Add(TradeAudit.From(req));
        await db.SaveChangesAsync();
    });
    return TypedResults.Accepted("/orders");
});

go deeper

for a junior

Remember that scoped services need a scope and that outside a request you create one with IServiceScopeFactory before resolving them.

for a middle

Explain CreateAsyncScope returning AsyncServiceScope, await using, why Dispose() throws for async-only disposables, and why resolved services must stay inside the block.

for a senior

Spot the fire-and-forget and startup-time variants in review, and move important off-request work to a hosted worker or queue rather than an untracked Task.Run.

for a principal

Set a convention for where off-request work may run and who owns its scope, so scope creation is centralised rather than scattered through singletons.

## Why off-request code needs its own scope In ASP.NET Core the framework creates a **scope** for every HTTP request and disposes it after the response. Scoped services, such as an EF Core `DbContext`, live inside that scope. Code that runs **outside** a request has no such scope: - a singleton refreshing a cache on a timer, - work done in `Program.cs` against `app.Services` before `app.Run()`, - a fire-and-forget task started by a handler that keeps running after the response. Each of these must create a scope of its own, or it ends up resolving scoped services from the root provider (rejected with "Cannot resolve scoped service ... from root provider." when `ValidateScopes` is on, silently promoted to app lifetime when it is off) or using a request's services after that request's scope has been disposed. ## The pattern `IServiceScopeFactory` is registered by the container itself as a singleton, and the scope validator explicitly accepts it as a dependency of singletons. Inject it, then: ```csharp public class TradeAuditWriter(IServiceScopeFactory scopes) { public async Task WriteAsync(TradeAudit audit, CancellationToken ct) { await using var scope = scopes.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService<TradingDbContext>(); db.TradeAudits.Add(audit); await db.SaveChangesAsync(ct); } // scope.DisposeAsync(): context and every disposable resolved here } ``` Rules that make it correct: 1. **One scope per unit of work.** One refresh, one message, one audit write. Everything resolved from `scope.ServiceProvider` in that unit shares one scoped instance per type, exactly as in a request. 2. **Resolve from the scope, not from the factory's provider.** `scope.ServiceProvider` is the scoped provider; `app.Services` and a singleton's injected `IServiceProvider` are the root. 3. **Nothing escapes.** Do not return the context, store it in a field or hand it to a task that outlives the `await using` block. After disposal the scope throws `ObjectDisposedException` on further resolution, and EF Core throws its own `ObjectDisposedException`: "Cannot access a disposed context instance." ## CreateScope versus CreateAsyncScope | | `CreateScope()` | `CreateAsyncScope()` | |---|---|---| | Declared on | `IServiceScopeFactory` (interface member) and `IServiceProvider` (extension) | extension on `IServiceScopeFactory` and on `IServiceProvider` | | Returns | `IServiceScope` | `AsyncServiceScope` (a readonly struct) | | Disposal | `using` calls `Dispose()` | `await using` calls `DisposeAsync()` | | Service implementing only `IAsyncDisposable` | `Dispose()` throws `InvalidOperationException` | disposed correctly | The scope disposes its tracked services in reverse order of creation. On the synchronous path, any service that implements `IAsyncDisposable` but not `IDisposable` makes `Dispose()` throw "'X' type only implements IAsyncDisposable. Use DisposeAsync to dispose the container." On the asynchronous path, `DisposeAsync` is awaited on every service that implements `IAsyncDisposable` and `Dispose` is called on the rest. Because any library type you resolve may implement only `IAsyncDisposable`, `CreateAsyncScope` with `await using` is the safe default in async code; `CreateScope` remains fine in synchronous code whose services are all `IDisposable`. ## The fire-and-forget trap in a handler A common bug in a trading dashboard: after accepting an order, a handler starts `Task.Run` to write an audit row using the `TradingDbContext` it was injected with. The response returns, the request scope is disposed, the context is disposed with it, and the background write fails with "Cannot access a disposed context instance." The fix is to give the task its own scope: ```csharp app.MapPost("/orders", (OrderRequest req, IServiceScopeFactory scopes) => { _ = Task.Run(async () => { await using var scope = scopes.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService<TradingDbContext>(); db.TradeAudits.Add(TradeAudit.From(req)); await db.SaveChangesAsync(); }); return TypedResults.Accepted("/orders"); }); ``` Even fixed, an untracked `Task.Run` is lost if the process stops, and its exceptions go unobserved; durable or important work belongs in a hosted background worker or a job queue, which is a separate topic. ## Mistakes reviewers catch - **`using` instead of `await using`** around `CreateScope()` in async code: works until a scoped service turns out to be async-only disposable, then throws at the end of the block. - **Opening the scope once in a constructor** and keeping it in a field: that scope never ends, so it is a captive dependency with extra steps. - **Resolving from the root** with `app.Services.GetRequiredService<TradingDbContext>()` at startup instead of opening a scope. - **Sharing one scope across parallel work.** Services in a scope, such as a `DbContext`, are not thread-safe; parallel branches each need their own scope. ## What to say in an interview - Off-request code needs its own scope; `IServiceScopeFactory` is the singleton-safe way to make one. - Prefer `await using var scope = factory.CreateAsyncScope();` in async code. - Resolve from `scope.ServiceProvider`, keep the work inside the block, and let the scope dispose what it created.

  • Why can a singleton take IServiceScopeFactory when it cannot take a scoped service?
    The container registers `IServiceScopeFactory` itself as a root-level singleton, and the scope validator explicitly skips it when checking a singleton's graph. Holding the factory captures nothing short-lived; each scope it creates is owned and disposed by the code that opened it.
  • Is app.Services.CreateAsyncScope() different from injecting IServiceScopeFactory?
    In effect, no. The `IServiceProvider` overload of `CreateAsyncScope` resolves `IServiceScopeFactory` from that provider and calls it, so both create a fresh child scope of the root. Injection is preferred inside classes because it makes the dependency visible and testable.

  • Resolving the DbContext from app.Services gives you a fresh per-call context.
  • A singleton cannot depend on IServiceScopeFactory because the factory is scoped.
  • CreateScope and CreateAsyncScope behave the same with async-only disposables.
  • A fire-and-forget task can keep using the request's injected DbContext safely.
  • You should call Dispose on each service resolved from the scope yourself.