Blazor 全局单例对象 - 使用依赖注入?

Blazor Global Singleton Object - use Dependency Injection?

我有一个 CUSTOMER 对象需要访问/可供 Blazor 应用程序的所有部分使用,从 MainLayout 到 NavMenu 再到 razor 组件。如何实现全局单例对象?

我曾尝试像这样在 Startup.cs 中使用 DI

services.AddSingleton<ICustomer, Customer>();

然后在MainLayout

@inject Customer cust

然后设置一些属性。

然后在CustomerPage

  @inject Customer cust

但客户页面中的值为空

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

你应该通过接口注入:

@inject ICustomer cust

或者自己注册class:

services.AddSingleton<Customer, Customer>();

@inject Customer cust