My web app has a background service that listens to a service bus. Based on the docs, it looks like the built-in way to run a background service is to implement IHoste
Based on your answers, I made a helpful extension method. It allows to register an IHostedService with another interface.
The other interface doesn't need to implement IHostedService, so you don't expose the StartAsync() and StopAsync() methods
public static class ServiceCollectionUtils
{
public static void AddHostedService(this IServiceCollection services)
where TService : class
where TImplementation : class, IHostedService, TService
{
services.AddSingleton();
services.AddHostedService>();
}
private class HostedServiceWrapper : IHostedService
{
private readonly IHostedService _hostedService;
public HostedServiceWrapper(TService hostedService)
{
_hostedService = (IHostedService)hostedService;
}
public Task StartAsync(CancellationToken cancellationToken)
{
return _hostedService.StartAsync(cancellationToken);
}
public Task StopAsync(CancellationToken cancellationToken)
{
return _hostedService.StopAsync(cancellationToken);
}
}
}