ASP.NET Core Web API Interview Question #166

How should a hosted service use scoped dependencies such as DbContext?

Testing, HttpClient, Integration Testing, Background Services & Deployment Senior Advanced

Quick Interview Answer

Hosted services are normally registered as singletons, so they should not directly capture a scoped DbContext. Instead, inject IServiceScopeFactory, create a scope for each unit of work, and resolve scoped services from that scope.

Detailed Explanation

Hosted services are normally registered as singletons, so they should not directly capture a scoped DbContext. Instead, inject IServiceScopeFactory, create a scope for each unit of work, and resolve scoped services from that scope.

Dispose the scope after the operation so scoped resources have the correct lifetime.

Code Example

using var scope = _scopeFactory.CreateScope();

var db = scope.ServiceProvider
    .GetRequiredService<AppDbContext>();

await ProcessAsync(db, stoppingToken);