An authorization handler accesses a DbContext. What is a potential concurrency issue with this code if the DbContext were incorrectly registered as a singleton service?

.NET interview question for Advanced practice.

Answer

If dbContext is a singleton, it is not thread-safe. Multiple concurrent requests could use it simultaneously, leading to data corruption or exceptions.

Explanation

The primary issue is A. Entity Framework's DbContext is not thread-safe and is designed for a short-lived, scoped lifetime (one instance per HTTP request). If it were incorrectly registered as a singleton, multiple concurrent requests would share the same instance, leading to race conditions, data tracking errors, and unpredictable exceptions. The fix is to ensure the DbContext is registered with a scoped lifetime (builder.Services.AddDbContext<MyDbContext(...)), which is the default.

Related Questions