[Question] Blazor Server, Mediator and Entity Framework Core Design Issue
See original GitHub issueWe have run into an issue in our application that is crashing the site: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext.
Which lead me to this article: ASP.NET Core Blazor Server with Entity Framework Core (EFCore). The recommended approach is to create a DbContextFactory, which is then demonstrated like this:
using var context = DbFactory.CreateDbContext();
var contact = await context.Contacts.FirstAsync(c => c.Id == Wrapper.DeleteRequestId);
Using the Mediator pattern the code would like more like this:
var contact = await Mediator.Send(new GetContact());
The GetContactHandler’s constructor would then receive the context through dependency injection. I could change the GetContactHandler to receive an IDbContextFactory instead but I don’t always want to new up a new context. I think only the Blazor server interface should care about this problem and the deeper layer’s should not be adjusted to accomodate it.
What is the recommended way to handle this Blazor Server-Side concern with Mediator?
Issue Analytics
- State:
- Created 3 years ago
- Reactions:6
- Comments:26 (4 by maintainers)
Top GitHub Comments
This is the solution I came up with as well.
I created a AsyncScopedMediator class which implements an IScopedMediator interface that gets injected in my blazor components. The request handlers are injected with EF Core Repositories, but could easily be changed to accept a DbContext in the constructor.
The implementation has the scope logic contained within the IScopedMediator.Send method:
And I inject it in my components where I need the scoped dbcontext.
–
I also added a MemoryCacheBehavior which uses an ICacheableRequest which my request object above implements.
I did this to address the ServerPrerender double loading of database requests that happens within the OnInitializationAsync() method.
How about creating a support/facade class to create a scope when calling the mediatr methods? Something like this: