|
| 1 | +using System; |
| 2 | +using System.IO; |
1 | 3 | using System.Threading.Tasks; |
2 | 4 | using Microsoft.AspNetCore.Hosting; |
3 | 5 | using Microsoft.EntityFrameworkCore; |
| 6 | +using Microsoft.Extensions.Configuration; |
4 | 7 | using Microsoft.Extensions.DependencyInjection; |
5 | 8 | using Microsoft.Extensions.Hosting; |
| 9 | +using Serilog; |
6 | 10 |
|
7 | 11 | namespace Dotnet6.GraphQL4.Store.WebAPI |
8 | 12 | { |
9 | 13 | public static class Program |
10 | 14 | { |
11 | 15 | private static IHostBuilder CreateHostBuilder(string[] args) |
12 | 16 | => Host.CreateDefaultBuilder(args) |
| 17 | + .UseSerilog( |
| 18 | + (context, services, configuration) |
| 19 | + => configuration |
| 20 | + .ReadFrom.Configuration(context.Configuration) |
| 21 | + .ReadFrom.Services(services) |
| 22 | + .Enrich.FromLogContext() |
| 23 | + .WriteTo.Console()) |
13 | 24 | .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>()) |
14 | | - .UseDefaultServiceProvider((context, options) => |
15 | | - { |
16 | | - options.ValidateScopes = context.HostingEnvironment.IsDevelopment(); |
17 | | - options.ValidateOnBuild = true; |
18 | | - }); |
19 | | - |
| 25 | + .UseDefaultServiceProvider( |
| 26 | + (context, options) => |
| 27 | + { |
| 28 | + options.ValidateScopes = context.HostingEnvironment.IsDevelopment(); |
| 29 | + options.ValidateOnBuild = true; |
| 30 | + }); |
| 31 | + |
20 | 32 | public static async Task Main(string[] args) |
21 | 33 | { |
22 | | - var host = CreateHostBuilder(args).Build(); |
23 | | - await host.MigrateDatabaseAsync(); |
24 | | - await host.RunAsync(); |
| 34 | + var configuration = new ConfigurationBuilder() |
| 35 | + .SetBasePath(Directory.GetCurrentDirectory()) |
| 36 | + .AddJsonFile( |
| 37 | + path: "appsettings.json", |
| 38 | + optional: false, |
| 39 | + reloadOnChange: true) |
| 40 | + .AddJsonFile( |
| 41 | + path: $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", |
| 42 | + optional: true, |
| 43 | + reloadOnChange: true) |
| 44 | + .Build(); |
| 45 | + |
| 46 | + Log.Logger = new LoggerConfiguration() |
| 47 | + .ReadFrom.Configuration(configuration) |
| 48 | + .CreateLogger(); |
| 49 | + |
| 50 | + try |
| 51 | + { |
| 52 | + var host = CreateHostBuilder(args).Build(); |
| 53 | + await host.MigrateDatabaseAsync(); |
| 54 | + await host.RunAsync(); |
| 55 | + Log.Information("Stopped cleanly"); |
| 56 | + } |
| 57 | + catch (Exception ex) |
| 58 | + { |
| 59 | + Log.Fatal(ex, "An unhandled exception occured during bootstrapping"); |
| 60 | + } |
| 61 | + finally |
| 62 | + { |
| 63 | + Log.CloseAndFlush(); |
| 64 | + } |
25 | 65 | } |
26 | 66 |
|
27 | 67 | private static async Task MigrateDatabaseAsync(this IHost host) |
|
0 commit comments