在我的项目中,当项目开始时,我想在本地获得所有配置信息。我创建了一个ConfigurationManager服务,并将HttpClient注入其中。在Blazor组件上有生命周期事件,如OnInitializedAsync
,在组件创建时被调用。
protected override async Task OnInitializedAsync()
{
await ...
}
服务是否有类似的东西?
Program.cs包含以下
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddScoped<StateManager>();
await builder.Build().RunAsync();
}
使用builder.Servuces.AddScoped<StateManager>()
添加状态管理器不提供对服务的引用,因此不可能调用非静态方法,所以我尝试了这个
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
var http = new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) };
builder.Services.AddScoped(sp => http);
var state = new StateManager(http);
builder.Services.AddScoped(sp => state);
await state.LoadAsync();
await builder.Build().RunAsync();
}