6.5 — Scopes and IServiceScopeFactory¶
← Roadmap · Section: 6. Dependency Injection Prev: 6.4 Captive dependencies · Next: 6.6 Registration APIs
Markers: 🔥 💻 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
A scope is a temporary sub-container. Services resolved inside it are shared within it, and everything it created is disposed when the scope ends.
- ASP.NET Core creates one scope per HTTP request automatically and disposes it when the response completes.
- Outside a request there is no scope — background services, startup code and singletons have none.
- Create one with
IServiceScopeFactory.CreateScope(), and always wrap it inusing.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| Scope | an IServiceScope |
A temporary sub-container. Disposable. Owns what it creates. |
IServiceScopeFactory |
an interface | Creates scopes. Itself a singleton, so safe to inject anywhere. |
CreateScope() |
a method | Creates a new IServiceScope. Must be disposed. |
CreateAsyncScope() |
a method | Same, but supports IAsyncDisposable services. Use with await using. |
scope.ServiceProvider |
a property | The scoped container. Resolve from this, not the root. |
| Root scope | the application container | app.Services. Lives for the whole application. |
| Ambient scope | the one you are already in | A request has one; a background service does not. |
RequestServices |
a property on HttpContext |
The current request's scope. Already exists — do not create another. |
ObjectDisposedException |
an exception | What you get from using a service after its scope was disposed. |
The concept¶
What a scope actually is¶
A scope is a box with a lifetime. Ask it for a scoped service and it either builds one and remembers it, or hands back the one it already built. When the box is thrown away, everything disposable inside it is disposed.
That is the entire mechanism, and it explains both what "scoped" means and why disposal is automatic.
A picture: a hotel room key card. It works for the length of your stay, opens the same room every time, and stops working when you check out. Another guest's card opens a different room. The hotel — the root container — outlives every card.
Where scopes come from¶
In a web application you almost never create one, because the framework does it for you:
Request arrives
→ framework creates a scope
→ middleware, filters and your action all resolve from it
→ one DbContext, one repository, shared by all of them
→ response completes
→ scope disposed → DbContext disposed
That is why "scoped" and "per request" are used interchangeably. But they are not the same thing, and the difference is the whole point of this note:
Scoped means per scope. A request happens to be a scope. Not everything is a request.
Background services, hosted services and startup code have no ambient scope. So resolving a scoped service there throws:
InvalidOperationException: Cannot resolve scoped service 'AppDbContext' from root provider.
How it works¶
The simple version — creating one¶
public class ReportGenerator(IServiceScopeFactory scopeFactory)
{
public async Task GenerateAsync(CancellationToken ct)
{
using var scope = scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var orders = await db.Orders.AsNoTracking().ToListAsync(ct);
// ... use them ...
} // scope disposed here → DbContext disposed
}
Three things must be right:
Inject IServiceScopeFactory, not IServiceProvider. The factory is a singleton, so no
lifetime mismatch. IServiceProvider injected into a singleton gives you the root provider,
and resolving scoped services from it recreates the captive dependency problem
(6.4).
Resolve from scope.ServiceProvider, not the outer provider. That is the whole point of
creating it.
using — without disposal the scope leaks, and so does everything it created.
Async disposal¶
If any service implements IAsyncDisposable — DbContext does — use the async variant:
await using var scope = scopeFactory.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
// ...
⚠️ Disposing an IAsyncDisposable service synchronously throws in some cases, and blocks a
thread in others. CreateAsyncScope was added because CreateScope could not dispose those
correctly. Prefer it when the scope holds anything async-disposable —
1.21.
⚠️ Do not create a scope inside a request¶
A request already has one:
// ✗ WRONG — creates a SECOND scope inside a request that already has one
public class OrdersController(IServiceScopeFactory factory) : ControllerBase
{
public async Task<IActionResult> Get()
{
using var scope = factory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
// A DIFFERENT DbContext from the one the rest of the request is using
}
}
That gives you two DbContext instances in one request, in separate change trackers and
separate transactions. Saving in one does not see pending changes in the other, which produces
genuinely confusing bugs.
// ✓ Just inject it — the request scope supplies it
public class OrdersController(AppDbContext db) : ControllerBase { }
The rule: create a scope only where there is not one already.
How it actually works — the three places you do need one¶
1. Startup work in Program.cs:
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.MigrateAsync();
}
app.Run();
Here app.Services is the root provider, and calling CreateScope() on it is correct — that
is how you get a scope from the root.
2. Background services — the most common case (21.2):
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
using (var scope = scopeFactory.CreateScope()) // INSIDE the loop
{
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await ProcessBatchAsync(db, stoppingToken);
}
await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
}
}
⚠️ Inside the loop, not outside. A scope held for the whole loop is a DbContext that
accumulates every entity from every iteration.
3. A singleton that occasionally needs scoped work:
public class PriceCache(IServiceScopeFactory scopeFactory) : IPriceCache
{
private readonly ConcurrentDictionary<string, decimal> _cache = new();
public async Task RefreshAsync(CancellationToken ct)
{
using var scope = scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
foreach (var price in await db.Prices.AsNoTracking().ToListAsync(ct))
_cache[price.Sku] = price.Amount;
}
}
The deeper detail — what disposal actually covers¶
When a scope is disposed, it disposes every disposable service it created — including transients.
using (var scope = scopeFactory.CreateScope())
{
var a = scope.ServiceProvider.GetRequiredService<ITransientDisposable>();
var b = scope.ServiceProvider.GetRequiredService<ITransientDisposable>();
// two separate instances — BOTH tracked by this scope
} // BOTH disposed here
⚠️ That has a consequence for long-lived scopes. Transient disposables are not released when you stop using them — they are held until the scope ends. In a long-running scope they accumulate, which is a real leak. See 6.10.
⚠️ And services resolved from the root are never disposed until shutdown, which is another
reason not to resolve scoped things from app.Services.
Code¶
The complete background service pattern, which is the case worth memorising:
public class OutboxProcessor(
IServiceScopeFactory scopeFactory,
ILogger<OutboxProcessor> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
// Fresh scope per iteration. Async, because DbContext is IAsyncDisposable.
await using var scope = scopeFactory.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var bus = scope.ServiceProvider.GetRequiredService<IMessageBus>();
var pending = await db.OutboxMessages
.Where(m => m.SentAt == null)
.OrderBy(m => m.CreatedAt)
.Take(100)
.ToListAsync(stoppingToken);
foreach (var message in pending)
{
await bus.PublishAsync(message.Payload, stoppingToken);
message.SentAt = DateTimeOffset.UtcNow;
}
await db.SaveChangesAsync(stoppingToken);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break; // shutting down — normal
}
catch (Exception ex)
{
logger.LogError(ex, "Outbox processing failed, will retry");
}
await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
}
}
}
Five decisions in that code, each worth being able to justify:
IServiceScopeFactory, notIServiceProvider— a real scope, not the root.- The scope is inside the loop, so each batch gets a fresh
DbContext. CreateAsyncScopewithawait using, becauseDbContextisIAsyncDisposable.- Cancellation is caught separately and treated as normal shutdown, not an error (2.14).
- Other exceptions do not kill the loop — an unhandled exception in a
BackgroundServicestops it silently while the app keeps running and looks healthy.
Interview questions¶
Q: What is a scope in ASP.NET Core dependency injection?
A scope is a temporary sub-container. Scoped services resolved from it are created once and shared within it, and when the scope is disposed everything disposable it created is disposed too. In a web application the framework creates a scope per HTTP request and disposes it when the response completes, which is why "scoped" and "per request" get used interchangeably. But they are not the same thing — scoped means per scope, and a request just happens to be one. Anything outside a request, like a background service or startup code, has no ambient scope at all.
Q: How do you use a scoped service in a background service?
Inject IServiceScopeFactory, call CreateScope — or CreateAsyncScope if anything is
IAsyncDisposable — and resolve from that scope's provider, wrapped in a using. The critical
detail is creating it inside the work loop rather than outside, because a scope held for the
service's whole lifetime gives you a single DbContext whose change tracker grows on every
iteration, which is the captive dependency problem moved rather than solved.
Q: Why inject IServiceScopeFactory rather than IServiceProvider?
Because IServiceProvider injected into a singleton is the root provider, and resolving a
scoped service from the root creates it in the root scope — which lives for the whole
application. You have recreated exactly the captive dependency you were trying to avoid, just
less visibly, and scope validation will not catch it. IServiceScopeFactory is itself a
singleton so there is no lifetime mismatch, and it gives you a genuine short-lived scope.
Q: Should you create a scope inside a controller?
No — the request already has one, and injecting a service directly gives you it. Creating another
produces a second DbContext in the same request with its own change tracker and its own
transaction, so saving through one does not see pending changes in the other. That leads to bugs
that are very hard to reason about. The rule is to create a scope only where one does not already
exist.
Traps ⚠️¶
- Creating a scope inside a request gives you a second
DbContextwith a separate transaction. - Creating a scope outside a loop holds one
DbContextfor the loop's entire lifetime. - Injecting
IServiceProviderinto a singleton gives the root, not a scope. - Forgetting
usingleaks the scope and everything it created. CreateScopewithIAsyncDisposableservices can throw or block. UseCreateAsyncScope.- Using a service after its scope is disposed throws
ObjectDisposedException— common when a scope is disposed before an async operation completes. - Transient disposables are held until the scope ends, not when you finish with them.
HttpContext.RequestServicesis already the request scope — do not wrap it in another.
Related¶
- 6.3 Service lifetimes — what "scoped" means
- 6.4 Captive dependencies — what scopes prevent
- 6.10 Disposal — what a scope disposes
- 21.1 Background services — where this is needed
- 21.2 Scoped services in background services — the pattern in full
- 4.3 Program.cs — startup scopes
- 1.21 IDisposable — sync vs async disposal