Blazor WebAssembly:使用构造函数注入将 Blazored.LocalStorage 注入服务

Blazor WebAssembly: using Constructor injection for injecting Blazored.LocalStorage into a service

包裹Blazored.LocalStorage是:

a library to provide access to local storage in Blazor applications

将服务注入组件很容易:

@inject Blazored.LocalStorage.ILocalStorageService localStorage

如果我们想将它注入到后面的代码中:

[Inject]
private ILocalStorageService localStorage { get; set; }

但是假设我想将它注入到另一个服务中(比如集中控制):

public class StorageManagement
{
    public StorageManagement(LocalStorageService localStorage)
    {
        //How to initialize it here?
    }
}

我不知道如何在 StorageManagement 的构造函数中初始化服务实例以及如何在 Program.cs 中设置 StorageManagement 的构造函数的参数 :

builder.Services.AddSingleton(e => new StorageManagement(//?));

只需 builder.Services.AddBlazoredLocalStorage();builder.Services.AddBlazoredLocalStorage(config => config.JsonSerializerOptions.WriteIndented = true);,如 README 中所述。
然后 builder.Services.AddScoped<StorageManagement>();builder.Services.AddScoped(p => new StorageManagement(p.GetRequiredSerice<ILocalStorageService>()));

但是您的服务应该使用 ILocalStorageService 而不是 LocalStorageService 实例 :

public class StorageManagement
{
    public StorageManagement(ILocalStorageService localStorage)
    {
        //How to initialize it here?
    }
}

您没有在构造函数中使用接口 ILocalStorageServer,它应该是

public class StorageManagement
{
    private readonly ILocalStorageService LocalStorage;
    
    public StorageManagement(ILocalStorageService localStorage)
    {
        LocalStorage = localStorage;
    }
}