Handle DbContext and IDbContextFactory<T> lifetime in Blazor InteractiveServer
Hi, I have some trouble getting EfCore to run properly with Blazor components and pages. I scaffolded a project using the Identity UI template and implemented business logic.
I wanted to deploy a first version on production but I'm stuck with flaky instances of the DbContext.
For example, the autogenerated
Components/Account/Pages/Manage/Index.razor
page contains the following initialization method:
In the same razor file, I inject the factory for the DB context at the top;
I then update some properties in a method below:
This results in the following stacktrace:
I've read and understood this official guide to work with EfCore in Blazor apps, but even though I never use DbContext directly and always create an instance on the fly using IDbContextFactory<AppDbContext>
, I still get this error.
Here is the content of the IdentityUserAccessor
:
Why is this happening? What am I doing wrong? Thanks for your help in advance! 🚀🙌ASP.NET Core Blazor with Entity Framework Core (EF Core)
Learn how to use Entity Framework Core (EF Core) in Blazor apps.
ASP.NET Core Blazor authentication and authorization
Learn about Blazor authentication and authorization scenarios.
1 Reply
After much troubleshooting, I found the solution. I used
UserManager<ApplicationUser>
and RoleManager<IIdentityRole>
in both layouts and components, leading to simulatneous calls. Using the AuthenticationStateProvider
in layouts fixed the issue.