C#C
C#3y ago
Relevant

❔ How to restart a BackgroundService

Searching the internets, I seem to be finding answers that don't really seem right, and not good even if they are right.

Is there a way to get the instance of a hosted service that may have stopped so that I can restart it?

I tried this, but service ended up being
null
in this case:

using (var scope = serviceScopeFactory.CreateScope())
{
    var service = scope.ServiceProvider.GetService<MyBackgroundService>();

    if (service != null)
    {
        try
        {
            await service.StopAsync(default);
            await service.StartAsync(default);
        }
        catch (Exception ex)
        {
            Log.Error(ex, ex.Message);
        }
    }

}
Was this page helpful?