I added a background service that periodically does something, like the official sample.
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddHostedService<TimedHostedService>(); <-- here
services.AddSingleton<WeatherForecastService>();
}
The TimedHostedService has StartAsync
and StopAsync
. Ultimately, I want to call these in the web browser.
In the FetchData.razor
file in the default scaffolding, I tried to refer that service directly, but that did not work. So, I added Start
and Stop
method to the WeatherForecastService
and called them on the click event.
<button @onclick="()=> { ForecastService.Stop(); }">Stop</button>
Now, the problem is, that I don't know how to get the running instance of TimedHostedService
in the Stop
method of WeatherForecastService
.
public class WeatherForecastService
{
....
public void Stop()
{
//how to get TimedHostedService instance?
}
....
}
I have tried using dependency injection to get the service provider, but GetService
returned 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());
}
I question the wisdom of manipulating the service from the GUI but if you're sure you want this then it's about how to register that service.
In startup:
services.AddSingleton<TimedHostedService>();
services.AddHostedService(sp => sp.GetRequiredService<TimedHostedService>());
and then you can
@inject TimedHostedService TimedService
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With