ASP.NET Core MVC Interview Question #128

Why is DbContext normally registered as a scoped service?

Dependency Injection, Services, Error Handling, Logging & Performance Senior Advanced

Quick Interview Answer

Entity Framework Core DbContext represents a unit of work and is not thread-safe. In a typical web application, a scoped lifetime allows services participating in one HTTP request to share the same request-level context while keeping contexts separate across requests.

Detailed Explanation

Entity Framework Core DbContext represents a unit of work and is not thread-safe. In a typical web application, a scoped lifetime allows services participating in one HTTP request to share the same request-level context while keeping contexts separate across requests.

A DbContext should not normally be stored in a singleton or shared concurrently between threads. Long-running background work should create and manage an appropriate scope or context independently.

Code Example

builder.Services.AddDbContext<AppDbContext>(options =>
{
    options.UseSqlServer(connectionString);
});