Blazor全局Singleton对象使用依赖注入



我有一个CUSTOMER对象,它需要访问/可用于Blazor应用程序的所有部分,从MainLayout到NavMenu再到剃刀组件。如何实现全局Singleton对象?

我曾尝试在Startup.cs中使用DI,就像这个一样

services.AddSingleton<ICustomer, Customer>();

然后在MainLayout

@inject Customer cust

然后设置一些属性。

然后在客户页面

@inject Customer cust

但CUSTOMERPAGE 中的值为空

我错过了什么?我需要在整个应用程序中保持此对象。

您应该通过接口注入:

@inject ICustomer cust

或者自己注册类:

services.AddSingleton<Customer, Customer>();
@inject Customer cust

最新更新