I know a IHostedService that runs only one time sounds like a console application, but the reason I want to use it instead of a plain console application is:
- .net core introduces Generic Host for running non-http application
- A plain console application does not have DI, Logger, Configurations ready to use
By using the following code, I'm able to somewhat achieve this one-time behaviour, however, I could not find a way to gracefully exit the app after it finishes.
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) => { services.AddHostedService<StartUp>(); });
}
Where StartUp is a simple IHostedService
public class StartUp:IHostedService
{
private ILogger<StartUp> _logger;
public StartUp(ILogger<StartUp> logger)
{
_logger = logger;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("start async");
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("stop async");
return Task.CompletedTask;
}
}
How can I stop the app gracefully? Or if this is completely wrong, how should I implement this one-time application?