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
My little helper code in response to the excellent answer of jjxtra
///
/// Instead of calling service.AddHostedService you call this make sure that you can also access the hosted service by interface TImplementation
/// https://stackoverflow.com/a/64689263/619465
///
/// The service collection
public static void AddInjectableHostedService(this IServiceCollection services)
where TService : class
where TImplementation : class, IHostedService, TService
{
services.AddSingleton();
services.AddSingleton(provider => provider.GetRequiredService());
services.AddSingleton(provider => provider.GetRequiredService());
}
So this will allow you to register your IHostedService with
services
.AddInjectableHostedService();
Where MyHostedServiceType off course implements some interface (IExposeSomething) with things that you want to expose to other types.