SQL Server Interview Question #293

Why should DbContext usually be scoped per web request?

ASP.NET Core, EF Core & SQL Server Real-World Scenarios Senior Advanced

Quick Interview Answer

In ASP.NET Core, AddDbContext normally registers DbContext with scoped lifetime, which aligns well with one HTTP request and a logical unit of work. DbContext is not thread-safe and should not be shared concurrently across requests or long-lived singleton services. A very long-lived context can accumulate tracked entities and stale state. Background services or parallel operations should create appropriate independent scopes or contexts rather than sharing one request context.

Detailed Explanation

In ASP.NET Core, AddDbContext normally registers DbContext with scoped lifetime, which aligns well with one HTTP request and a logical unit of work.

DbContext is not thread-safe and should not be shared concurrently across requests or long-lived singleton services. A very long-lived context can accumulate tracked entities and stale state.

Background services or parallel operations should create appropriate independent scopes or contexts rather than sharing one request context.