Blazor:如何获取托管服务实例?
Blazor: How to get the hosted service instance?
我添加了一个后台服务,它会定期做一些事情,就像官方示例一样。
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddHostedService<TimedHostedService>(); <-- here
services.AddSingleton<WeatherForecastService>();
}
TimedHostedService有StartAsync
和StopAsync
。最终,我想在网络浏览器中调用这些。
在默认脚手架的 FetchData.razor
文件中,我尝试直接引用该服务,但没有成功。因此,我将 Start
和 Stop
方法添加到 WeatherForecastService
并在点击事件中调用它们。
<button @onclick="()=> { ForecastService.Stop(); }">Stop</button>
现在的问题是,我不知道如何在 WeatherForecastService
的 Stop
方法中获取 TimedHostedService
的 运行 实例。
public class WeatherForecastService
{
....
public void Stop()
{
//how to get TimedHostedService instance?
}
....
}
我试过使用依赖注入来获取服务提供者,但是GetService
返回了null。
IServiceProvider sp;
public WeatherForecastService(IServiceProvider sp)
{
this.sp = sp;
}
public void Stop()
{
var ts = sp.GetService(typeof(TimedHostedService)) as TimedHostedService;
ts.StopAsync(new CancellationToken());
}
我质疑从 GUI 操作服务是否明智,但如果您确定需要这个,那么它就是关于如何注册该服务的问题。
启动中:
services.AddSingleton<TimedHostedService>();
services.AddHostedService(sp => sp.GetRequiredService<TimedHostedService>());
然后你可以
@inject TimedHostedService TimedService
我添加了一个后台服务,它会定期做一些事情,就像官方示例一样。
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddHostedService<TimedHostedService>(); <-- here
services.AddSingleton<WeatherForecastService>();
}
TimedHostedService有StartAsync
和StopAsync
。最终,我想在网络浏览器中调用这些。
在默认脚手架的 FetchData.razor
文件中,我尝试直接引用该服务,但没有成功。因此,我将 Start
和 Stop
方法添加到 WeatherForecastService
并在点击事件中调用它们。
<button @onclick="()=> { ForecastService.Stop(); }">Stop</button>
现在的问题是,我不知道如何在 WeatherForecastService
的 Stop
方法中获取 TimedHostedService
的 运行 实例。
public class WeatherForecastService
{
....
public void Stop()
{
//how to get TimedHostedService instance?
}
....
}
我试过使用依赖注入来获取服务提供者,但是GetService
返回了null。
IServiceProvider sp;
public WeatherForecastService(IServiceProvider sp)
{
this.sp = sp;
}
public void Stop()
{
var ts = sp.GetService(typeof(TimedHostedService)) as TimedHostedService;
ts.StopAsync(new CancellationToken());
}
我质疑从 GUI 操作服务是否明智,但如果您确定需要这个,那么它就是关于如何注册该服务的问题。
启动中:
services.AddSingleton<TimedHostedService>();
services.AddHostedService(sp => sp.GetRequiredService<TimedHostedService>());
然后你可以
@inject TimedHostedService TimedService