在Program.cs文件中注册services.AddSingleton
在Program.cs文件中注册服务:
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add("app");
builder.Services.AddSingleton();
await builder.Build().RunAsync();
}
在组件中使用@inject注入状态容器:
@inject StateContainer state
Count: @state.Count
@code {
private void IncrementCount()
{
state.Count++;
}
}