简体   繁体   English

Blazor 服务器作用域在刷新页面时再次初始化

[英]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.我创建了一个简单的 Blazor 服务器应用程序:在组件中注入了 class “UserSettings.cs”。

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

I display the Id inside the UserSetting Service in different Components.我在不同组件中的 UserSetting 服务中显示 Id。 After switching the component, the Id stays the same, but when i refresh the page, it changes.切换组件后,Id 保持不变,但是当我刷新页面时,它会发生变化。 Why does the Service initialized again when refreshing the page?为什么刷新页面时Service又初始化了?

Your service is scoped to the circuit connection...When you refresh the page, a new circuit object is created.您的服务范围仅限于电路连接...当您刷新页面时,会创建一个新电路 object。 You may use the AddSingleton instead, but in that case all your users may see the same ID.您可以改用 AddSingleton,但在这种情况下,您的所有用户可能会看到相同的 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?为什么不在你的App第一次渲染的时候创建Id,保存在session存储或者本地存储中使用呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM