Created
November 15, 2019 18:07
-
-
Save jdharmon/06ba4644d6fc421f0a759a1502b43014 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using Microsoft.Extensions.Configuration; | |
| using Microsoft.Extensions.DependencyInjection; | |
| using Microsoft.Extensions.Logging; | |
| using System; | |
| using System.IO; | |
| using System.Runtime.Loader; | |
| using System.Threading; | |
| using System.Threading.Tasks; | |
| namespace MyApp | |
| { | |
| class Program | |
| { | |
| private static IConfiguration Configuration; | |
| private static async Task Main(string[] args) | |
| { | |
| var environment = Environment.GetEnvironmentVariable("NETCORE_ENVIRONMENT") ?? "Production"; | |
| Console.WriteLine($"Environment: {environment}"); | |
| var basePath = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location); | |
| Configuration = new ConfigurationBuilder() | |
| .SetBasePath(basePath) | |
| .AddJsonFile($"appsettings.json", optional: false) | |
| .AddJsonFile($"appsettings.{environment}.json", optional: true) | |
| .AddEnvironmentVariables() | |
| .AddCommandLine(args) | |
| .Build(); | |
| var serviceCollection = new ServiceCollection(); | |
| ConfigureServices(serviceCollection); | |
| var serviceProvider = serviceCollection.BuildServiceProvider(); | |
| CancellationTokenSource cts = new CancellationTokenSource(); | |
| var service = serviceProvider.GetRequiredService<MyService>(); | |
| var task = service.RunAsync(cts.Token); | |
| Console.WriteLine("Service is running. Press Ctrl+C to shut down."); | |
| WaitForExitSignal(); | |
| cts.Cancel(); | |
| await task; | |
| } | |
| private static void WaitForExitSignal() | |
| { | |
| using (var signal = new ManualResetEventSlim()) | |
| { | |
| // Handle SIGTERM | |
| AssemblyLoadContext.Default.Unloading += _ => signal.Set(); | |
| // Hadle SIGINT/Ctrl+C | |
| Console.CancelKeyPress += (s, a) => | |
| { | |
| a.Cancel = true; | |
| signal.Set(); | |
| }; | |
| //Block until signaled | |
| signal.Wait(); | |
| } | |
| } | |
| private static void ConfigureServices(IServiceCollection services) | |
| { | |
| services.AddSingleton(Configuration); | |
| services.AddLogging(logging => | |
| { | |
| logging.AddConfiguration(Configuration.GetSection("Logging")); | |
| logging.AddConsole(); | |
| }); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment