.NET › Dependency Injection
How do you use IServiceScopeFactory to manually create and manage a DI scope outside the normal request pipeline?
AdvancedAnswer
IServiceScopeFactory.CreateScope() returns an IServiceScope (implementing IDisposable) whose ServiceProvider can resolve scoped services within that isolated scope's lifetime -- essential for singleton or background contexts (like a BackgroundService or a Console app's Main method) that have no natural per-request scope but still need to consume scoped services like a DbContext, ensuring proper disposal via a using block once the unit of work completes.
public class ReportGenerator : BackgroundService {
private readonly IServiceScopeFactory _scopeFactory;
protected override async Task ExecuteAsync(CancellationToken ct) {
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await GenerateReportAsync(db);
} // scope disposed here, DbContext and other scoped services cleaned up
}Real-world example A console application's data migration tool creates a manual DI scope in its Main method to resolve and use scoped repository services exactly as they'd be used in a web request, despite having no actual HTTP request context.