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
.net core now has a AddHostedService overload that lets you specify a factory function/method for resolving hosted services. This lets you specify your hosted service as a singleton and then inject it where necessary.
Documentation says it's been available since .Net Core 3.x
Arguably, one should analyze the architecture choices that led to this path to ensure that this route is actually required. But sometimes it may be necessary.
AddHostedService(IServiceCollection, Func)
Usage is
services
.AddSingleton()
.AddHostedService(services => (MyServiceImplementation) services.GetService())
;
If your IServiceContract inherits from IHostedService or you don't use an interface then the cast is unnecessary.