C
C#15mo 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);
}
}

}
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);
}
}

}
4 Replies
JakenVeina
JakenVeina15mo ago
you'd have to register it manually if you're registering it currently with .AddHostedService<T>(), that only registers it as IHostedService you would need an alias registration
.AddSingleton<MyService>()
.AddSingleton<IHostedService>(serviceProvider => serviceProvider.GetRequiredService<MyService>()
.AddSingleton<MyService>()
.AddSingleton<IHostedService>(serviceProvider => serviceProvider.GetRequiredService<MyService>()
I wouldn't recommend this, though that's going to screw up the lifetime management of the service
Relevant
Relevant15mo ago
Yeah makes sense. And actually after thinking about it more, I realized that the service wasn't actually stopped. The ExecuteAsync method calls 2 method and one of them was working, and the other wasn't. So I'm guessing maybe the cancellation token cancelled or an exception was thrown and returned out of the method
JakenVeina
JakenVeina15mo ago
yeah, what you'd want to do if you experience one of your services crashing, is put error-handling and restart behavior inside that service itself that's not really the host's job
Accord
Accord15mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.