using IHostedService for a cron job

So you want to make a console application using .net, but you also want the ease of dependency injection?

Use a host builder like the generic host: this gets you the DI you want, plus reading of appsettings, parsing out the environment, etc for "free". Simply add one (or more!) IHostedServices (e.g. BackgroundService)

The downside is that it really seems to be meant more for worker processes like an event listener, something that runs in a loop until it gets a SIGTERM. For a cron job or other one-off process this isn't ideal, because it will run your code in ExecuteAsync()[1] and then just... sit there.

You have a few options: in the past I've explicitly called Environment.Exit(0) but that seemed... inelegant[2]. Instead, you're able to say "and then pack it all in because we're done": inject an instance of IHostApplicationLifetime through the constructor of your IHostedService, then call _applicationLifetime.StopApplication()!


  1. assuming you're extending BackgroundService ↩︎

  2. and may not respect application lifetimes and graceful shutdown: I admit I haven't checked ↩︎