C
C#6mo ago
Pingu

Blazor .net8 DI state sharing between client and server

Heya. I'm only now getting to taking a look at some of the new bits of .net 8 and Blazor. I am a little confused with this dual project setup, how I would inject some stateful services. Minimal example, so not useful in itself but illustrates the point nicely... I generally expect to have my components and pages rendered as static SSR where possible, and where interactivity is required I expect to use auto, so things could be server or client rendered depending. Now, take this example service (attached image)... Adding that as a singleton in the client project and scoped in the server project, I get different values for it depending on whether the component is rendered as static SSR, interactive server, or interactive WASM. (see image 2) Also in addition, when I navigate away (within the same app, not leaving or refreshing) from this page and come back, the GUID shown for interactive WASM and interactive Server remain the same as they were previously, which I expect. What I didn't expect however is that the static SSR component will get a new Guid each time I navigate to a different page and come back.
No description
No description
1 Reply
aquaritek
aquaritek6mo ago
You need to use an implementation of PersistentComponentState (https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.persistentcomponentstate?view=aspnetcore-8.0) For an example you can look at the new Identity Scaffold for Individual Accounts. They make use of it to pass authentication state to Wasm in Auto mode components.
PersistentComponentState Class (Microsoft.AspNetCore.Components)
The state for the components and services of a components application.