In Blazor Server, why is it dangerous to use a standard Scoped DbContext, and what is the recommended alternative?
Last updated
A Scoped service lives for the whole circuit, so one
DbContextis shared by all concurrent operations in a user's session. It is not thread-safe, so overlapping calls throw "A second operation was started on this context".A long-lived context also accumulates tracked entities and stale data.
Instead register
AddDbContextFactoryand injectIDbContextFactory<T>. Create a short-lived context per operation withawait using var db = factory.CreateDbContext().
- https://dev.to/stevsharp/when-idbcontextfactory-enters-the-chat-and-what-it-actually-fixes-52i4
- https://medium.com/@drift2galaxy/asp-net-core-blazor-with-entity-framework-core-ef-core-%E5%A6%82%E4%BD%95%E6%B3%A8%E5%85%A5dbcontext-d4fa2ff16822
- https://learn.microsoft.com/en-us/aspnet/core/blazor/blazor-ef-core?view=aspnetcore-10.0
- https://blog.stackademic.com/from-bug-farm-to-bulletproof-mastering-dbcontext-vs-idbcontextfactory-without-burning-your-app-61e3b4e3a9e0
- https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/
- https://learn.microsoft.com/en-us/answers/questions/1281629/is-it-thread-safe-to-use-dbcontext-in-blazor-serve