Entity Framework Core Interview Question #185

How should EF Core be used in background services?

Testing, Production Practices & Senior Real-World Scenarios Senior Advanced

Quick Interview Answer

Background services are often singleton services, while DbContext is normally scoped. Create a scope or use IDbContextFactory for each bounded unit of background work rather than injecting a scoped DbContext directly into a singleton. Dispose each context and honor cancellation tokens so shutdown and retries are controlled.

Detailed Explanation

Background services are often singleton services, while DbContext is normally scoped. Create a scope or use IDbContextFactory for each bounded unit of background work rather than injecting a scoped DbContext directly into a singleton. Dispose each context and honor cancellation tokens so shutdown and retries are controlled.

Code Example

await using var db =
    await _dbContextFactory.CreateDbContextAsync(stoppingToken);

await ProcessBatchAsync(db, stoppingToken);