ASP.NET Core Interview Question #164
How should a BackgroundService use scoped services such as DbContext?
Logging, Error Handling & Background Services Mid-Level Intermediate
Quick Interview Answer
A hosted BackgroundService is long-lived, whereas DbContext is normally scoped. Injecting the DbContext directly into the worker would create a lifetime mismatch.
Detailed Explanation
A hosted BackgroundService is long-lived, whereas DbContext is normally scoped. Injecting the DbContext directly into the worker would create a lifetime mismatch.
Instead, inject IServiceScopeFactory. For each unit of work, create a scope, resolve the scoped service or DbContext, complete the operation, and dispose the scope.
This ensures each operation gets correctly scoped dependencies and prevents a DbContext from being shared across unrelated background operations.
Code Example
public class CleanupWorker : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
public CleanupWorker(IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
using var scope = _scopeFactory.CreateScope();
var service = scope.ServiceProvider
.GetRequiredService<ICleanupService>();
await service.RunAsync(stoppingToken);
await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
}
}
}