Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor Server Scoped Inititialized again on refreshing the page

I created a simple Blazor Server Application: The class "UserSettings.cs" is injected in the components.

     public class UserSettings
     {
         public Guid Id{ get; } = Guid.NewGuid();
     }
 
     services.AddScoped<UserSettings>();

I display the Id inside the UserSetting Service in different Components. After switching the component, the Id stays the same, but when i refresh the page, it changes. Why does the Service initialized again when refreshing the page?

like image 541
Simon Libbs Avatar asked Sep 17 '25 03:09

Simon Libbs


1 Answers

Your service is scoped to the circuit connection...When you refresh the page, a new circuit object is created. You may use the AddSingleton instead, but in that case all your users may see the same ID.

Why not create the Id when your App is rendered for the first time, and save it in a session storage or local storage for use ?

like image 129
enet Avatar answered Sep 19 '25 10:09

enet