2

I've written a console app that uses the Generic host mostly to take advantage of its IOC container and to keep the application consistent with our ASP.NET Core applications.

A basic question for you. Host do I have the host shutdown automatically after the start code runs (not wait for Ctrl-C).

Jason

JasonDWilson
  • 503
  • 4
  • 10

3 Answers3

2

There is a special interface for this, the IApplicationLifetime.

Have this injected in your constructor and call StopApplication() on it for a gracefull shutdown. This also allows you to handle the startup & shutdown of the application in other places so you don't need to coordinate this yourself.

You can read more about this here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host#iapplicationlifetime-interface

Robin Krom
  • 180
  • 8
1

Environment.Exit(0);

Try to call this at the end of your execution point. But it might not work properly if you have some other threads, unmanaged resources or other unpredictable stuff in your code.


Other thing is that you probably don't have to use the GenericHost at all. See the answer to this question. It might point you how to create the DI container without the GenericHost.

rudolfdobias
  • 1,778
  • 3
  • 17
  • 40
0

You can use host.StartAsync()

static async Task<int> Main(string[] args) 
{
    using var host = CreateHostBuilder(args).Build();
    await host.StartAsync();
}
tstojecki
  • 1,480
  • 2
  • 19
  • 29