在 Blazor 中,单例对象会在导航时重新创建,因为每次导航都会重新加载整个页面。但是,你可以通过使用服务容器来解决这个问题,确保单例对象在导航期间保持不变。
下面是一个示例代码,展示了如何在 Blazor 中实现单例对象的解决方案:
public class SingletonService
{
public int Counter { get; set; } = 0;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton();
}
@inject SingletonService singletonService
Counter: @singletonService.Counter
通过以上步骤,SingletonService 将会成为一个单例对象,并且在导航期间保持不变。无论多次导航,都会使用同一个实例。
注意:如果你需要在组件中修改 SingletonService 的属性,确保使用的是同一个实例,可以通过在组件中注入 IServiceProvider,并使用 GetRequiredService
@inject IServiceProvider serviceProvider
...
SingletonService singletonService = serviceProvider.GetRequiredService();
这样就能确保在组件中使用的是同一个 SingletonService 实例。
希望以上解决方法能帮助到你!
上一篇:Blazor CSS未加载