Reputation: 190
I am currently building a Blazor server project with .NET6. Anyway, I am not certain on what today's best practices are for structuring components.
This post describes on how I generally structure the project. I basically have an MVVM pattern. Views (e.g., MyView.razor) have their corresponding ViewModels (e.g., MyView.razor.cs) and ViewModels can consume Services, which are injected by the IoC container.
I ran into some issues where concurrent read/writes on our DB context occurred, as soon the project tried to fetch data from the Azure SQL DB. Making the DB context transient in the Startup.cs did not help. Back then, when I ran into this issue the first time, I stumbled over a similar issue on StackOverflow (which I cannot find anymore), which stated that this issue occurs when child components use a DB service and this should be avoided.
I fixed the issue with the help of the named post by doing the following: ALL DB calls are now in the "Root ViewModel" (e.g., MyPage.razor). Corresponding data is then passed down with parameters to the child components. This means that only my root ViewModel has any services injected. For nested components, this adds an additional overhead of passing the corresponding parameters and making sure that the properties are then updated correctly (which is sometimes very frustrating, especially if you are down 3 layers of nested components).
Now my question: Is this really the best practise to do it like that?
Upvotes: 0
Views: 591
Reputation: 52365
My guess is you are using Blazor Server. Microsoft has issued specific guidelines for using EF core with Blazor Server. You can find them here. In short, once that SignalR connection is established, the state remains indefinitely. This doesn't match with the EF core model, so I suggest you use IDBContextFactory as they recommend.
Upvotes: 1