.NET Architecture & System Design Interview Question #50

How should scoped services be used inside a BackgroundService?

Caching, CDN, Queues & Asynchronous Processing Junior Beginner

Quick Interview Answer

BackgroundService is normally registered as a singleton, so it should not capture scoped dependencies such as an EF Core DbContext directly through its constructor.

Detailed Explanation

BackgroundService is normally registered as a singleton, so it should not capture scoped dependencies such as an EF Core DbContext directly through its constructor.

Instead, inject IServiceScopeFactory, create a scope for an appropriate unit of work, resolve scoped services from that scope, complete the work, and dispose the scope.

Code Example

public class Worker(IServiceScopeFactory scopes)
    : BackgroundService
{
    protected override async Task ExecuteAsync(
        CancellationToken token)
    {
        using var scope = scopes.CreateScope();
        var db = scope.ServiceProvider
            .GetRequiredService<AppDbContext>();

        await ProcessAsync(db, token);
    }
}