Advertisement
Intermediate ASP.NET Core, Dependency Injection

How do you use IServiceScopeFactory to manually create a DI scope outside the normal per-request pipeline, such as inside a background service?

Short answer

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) that have no natural…

Save ASP.NET Core mock interview
Advertisement
AModel answer
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) 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(IServiceScopeFactory scopeFactory) : BackgroundService {
    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 cleaned up
}
Real-world example
A background report-generation service creates a manual DI scope for each report run, resolving scoped repository services exactly as they'd be used in a web request, despite having no actual HTTP request context.
Likely follow-ups
  • What happens to scoped services if you never dispose the created scope?
  • How does this differ from calling IServiceProvider.CreateScope() directly?
Related topics