Entity Framework Core Interview Question #183

Why should a DbContext usually be short-lived?

Testing, Production Practices & Senior Real-World Scenarios Senior Advanced

Quick Interview Answer

A long-lived DbContext can accumulate many tracked entities, consume memory, retain stale data, and make unit-of-work boundaries unclear. A short-lived context keeps tracking manageable and makes transaction and persistence behavior easier to reason about. Background or batch workloads should create appropriately bounded contexts rather than keeping one forever.

Detailed Explanation

A long-lived DbContext can accumulate many tracked entities, consume memory, retain stale data, and make unit-of-work boundaries unclear. A short-lived context keeps tracking manageable and makes transaction and persistence behavior easier to reason about. Background or batch workloads should create appropriately bounded contexts rather than keeping one forever.

Code Example

await using var db =
    await dbContextFactory.CreateDbContextAsync(cancellationToken);

// Perform one bounded unit of work.