Stop console application that is using DI and a hosted service for user code

Viewed 419

I am building a console application that is supposed to stop running after several hours. I used dependency injection to get instances of my services, and my main service is registered as a Hosted service to act as an entrypoint for my code.

After the application has done it's job and the executable should stop running. If I call StopAsync() on the service, it runs the method but doesn't kill the executable. How do I exit the program?

Program.cs

class Program
{
    private static readonly Logger _logger = LogManager.GetCurrentClassLogger();

    public static void Main(string[] args)
    {
        _logger.Info($"starting execution of Program.Main()");

        CreateHostBuilder(args).Build().Run();

        _logger.Info($"finished execution of Program.Main()");
    }

    public static IHostBuilder CreateHostBuilder(string[] args)
    {
        IConfiguration Configurations = new ConfigurationBuilder()
            .SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
#if DEBUG
            .AddUserSecrets("secrets guid")
#endif
            .Build();

        return Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostContext, builder) => builder.AddConfiguration(Configurations))
            .ConfigureServices(services =>
            {
                services.AddHostedService<MainService>();

                services.AddScoped<Service1>();
                services.AddScoped<Service2>();
                services.AddScoped<Service3>();

                services.AddDbContext<pig_dbContext>(options =>
                    options.UseMySql(Configurations.GetConnectionString("XXXX"), builder =>
                        builder.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), null)));
            });
    }
}

MainService.cs

public class MainService: IHostedService
{
    private static readonly Logger _logger = LogManager.GetCurrentClassLogger();

    public MainService(Service1 service1, Service2 service2, Service3 service3, IServiceProvider services, IConfiguration config)
    {
        //...
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        //This method is called by .NET when calling Host.Run()
        ///Do work...

        //This call reaches the method, but does not end execution of the application. I want the application to completely exit.
        StopAsync(new CancellationToken());
    }
1 Answers

I figured it out: The host kept blocking the main thread, so using

CreateHostBuilder(args).Build().RunAsync();

fixed my issue :)

Related