Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor: How to get the hosted service instance?

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());
}
like image 650
Damn Vegetables Avatar asked Oct 16 '25 02:10

Damn Vegetables


1 Answers

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
like image 90
Henk Holterman Avatar answered Oct 18 '25 20:10

Henk Holterman