Entity Framework Core Interview Question #182
How should DbContext lifetime be managed in ASP.NET Core?
Testing, Production Practices & Senior Real-World Scenarios Senior Advanced
Quick Interview Answer
A DbContext is normally registered as scoped so one instance is available within a web-request scope. It represents a short-lived unit of work and should be disposed when the scope ends. DbContext is not thread-safe, so the same instance must not be used concurrently by multiple threads or parallel operations.
Detailed Explanation
A DbContext is normally registered as scoped so one instance is available within a web-request scope. It represents a short-lived unit of work and should be disposed when the scope ends. DbContext is not thread-safe, so the same instance must not be used concurrently by multiple threads or parallel operations.
Code Example
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(connectionString));