ASP.NET Core Web API Interview Question #103

Why is DbContext normally registered as a scoped service?

Dependency Injection, Services, EF Core, Async & Data Access Mid-Level Intermediate

Quick Interview Answer

A DbContext represents a unit of work and tracks entity state. In a typical Web API, one scoped DbContext per request provides a natural boundary for querying and saving related changes.

Detailed Explanation

A DbContext represents a unit of work and tracks entity state. In a typical Web API, one scoped DbContext per request provides a natural boundary for querying and saving related changes.

DbContext is not thread-safe and should not be shared concurrently across requests. Long-lived contexts can also accumulate tracked entities and stale state.

Code Example

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(
        builder.Configuration.GetConnectionString("Default")));