ASP.NET Core Interview Question #70
What is IServiceScopeFactory?
Dependency Injection & Services Junior Beginner
Quick Interview Answer
IServiceScopeFactory creates IServiceScope instances. It is especially useful in singleton services and background workers that need to resolve scoped dependencies for individual operations.
Detailed Explanation
IServiceScopeFactory creates IServiceScope instances. It is especially useful in singleton services and background workers that need to resolve scoped dependencies for individual operations.
The singleton keeps only the scope factory. For each unit of work it creates a scope, resolves the scoped service, completes the work, and disposes the scope.
This avoids injecting a scoped dependency directly into a singleton and preserves the intended lifetime of services such as DbContext.
Code Example
public class CleanupWorker : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
public CleanupWorker(IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var scope = _scopeFactory.CreateScope();
var service = scope.ServiceProvider
.GetRequiredService<ICleanupService>();
await service.RunAsync(stoppingToken);
}
}