admin管理员组

文章数量:1287514

I am in the process of converting a .NET 6 Blazor Server app to a .NET 8 Blazor Web app. Our app relies heavily on a scoped service to make data, obtained from the HttpContext of the initial page request, available to all of our Blazor views and components. As you might expect, this is data that is specific to each user session.

When I launched the Blazor Web App, I discovered that a scoped service created during the PreRender phase gets disposed and recreated during the Interactive phase. The solution recommended by Microsoft is to use the PersistentComponentState service.

Evidently, this requires adding code (to register with the PersistentComponentState service, plus calls to TryTakeFromJson and PersistAsJson) to every routable Blazor view, and the persist-component-state tag helper has to be added to Pages/Shared/_Layout.cshtml so that all embedded (i.e. non-routable) components can access the persisted state.

This is a deal breaker for us; we want to upgrade to .NET 8 without having to make extensive code modifications.

I tried disabling prerender globally by setting the @rendermode attribute (on both the HeadOutlet and Routes elements in App.razor) to: "new InteractiveServerRenderMode(prerender: false)" to see if the scoped service created upon application startup would persist, but the behavior did not change, i.e. a new instance of the service still got created. This was a disappointment, because it is forcing us to abandon the idea of taking advantage of the hybrid model, and instead do a more conservative upgrade to .NET 8 Server app.

Is there really no way to convert to a Blazor Server app to a Blazor Web App and still retain the behavior where a scoped service experiences a single instantiation?

本文标签: