11using System ;
22using System . Threading ;
33using System . Threading . Tasks ;
4- using Microsoft . Extensions . Configuration ;
54using Microsoft . Extensions . DependencyInjection ;
65using Microsoft . Extensions . Hosting ;
76using Microsoft . Extensions . Logging ;
@@ -14,37 +13,19 @@ public class Program
1413 {
1514 private static async Task Main ( )
1615 {
17- var config = new ConfigurationBuilder ( ) . Build ( ) ;
18-
19- var logger = LogManager . Setup ( )
20- . SetupExtensions ( ext => ext . RegisterHostSettings ( config ) )
21- . GetCurrentClassLogger ( ) ;
22-
23- try
24- {
25- var hostBuilder = new HostBuilder ( )
26- . ConfigureLogging ( builder => builder . SetMinimumLevel ( Microsoft . Extensions . Logging . LogLevel . Trace ) )
16+ // Disposing the Host will also flush / dispose / shutdown the NLog Logging Provider
17+ using var host = new HostBuilder ( )
2718 . ConfigureServices ( ( hostContext , services ) => services . AddHostedService < ConsoleHostedService > ( ) )
28- . UseNLog ( ) ;
19+ . UseNLog ( ) // Setup NLog for logging
20+ . UseConsoleLifetime ( )
21+ . Build ( ) ;
2922
30- // Build and run the host in one go; .RCA is specialized for running it in a console.
31- // It registers SIGTERM(Ctrl-C) to the CancellationTokenSource that's shared with all services in the container.
32- await hostBuilder . RunConsoleAsync ( ) ;
23+ // Build and run the host in one go; .RCA is specialized for running it in a console.
24+ // It registers SIGTERM(Ctrl-C) to the CancellationTokenSource that's shared with all services in the container.
25+ await host . RunAsync ( ) ;
3326
34- Console . WriteLine ( "The host container has terminated. Press ANY key to exit the console." ) ;
35- Console . ReadKey ( ) ;
36- }
37- catch ( Exception ex )
38- {
39- // NLog: catch setup errors (exceptions thrown inside of any containers may not necessarily be caught)
40- logger . Fatal ( ex , "Stopped program because of exception" ) ;
41- throw ;
42- }
43- finally
44- {
45- // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
46- LogManager . Shutdown ( ) ;
47- }
27+ Console . WriteLine ( "The host container has terminated. Press ANY key to exit the console." ) ;
28+ Console . ReadKey ( ) ;
4829 }
4930
5031 public class ConsoleHostedService : BackgroundService
0 commit comments