Advertisement
Guest User

Untitled

a guest
Sep 23rd, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.93 KB | None | 0 0
  1. public static class Program
  2. {
  3. private static readonly CancellationTokenSource TokenSource;
  4.  
  5. static Program()
  6. {
  7. TokenSource = new CancellationTokenSource();
  8. Console.CancelKeyPress += (sender, args) =>
  9. {
  10. TokenSource.Cancel();
  11. args.Cancel = true;
  12. };
  13. }
  14.  
  15. public static void Main(string[] args) =>
  16. MainAsync(args, TokenSource.Token).ConfigureAwait(false).GetAwaiter().GetResult();
  17.  
  18. private static async Task MainAsync(string[] args, CancellationToken ct)
  19. {
  20. if (TryConfigureLogging(out var loggerFactory, out var logger))
  21. {
  22. logger.LogInformation("Application started...");
  23.  
  24. if (TryBuildConfigurations(logger, args, out var configurationRoot))
  25. {
  26. if (TryBuildServiceProvider(logger, loggerFactory, configurationRoot, out var serviceProvider))
  27. {
  28. try
  29. {
  30. using (var scope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
  31. {
  32. await scope.ServiceProvider.GetRequiredService<Application>().RunAsync(ct)
  33. .ConfigureAwait(false);
  34. }
  35. }
  36. catch (TaskCanceledException)
  37. {
  38. logger.LogWarning("The application execution was canceled by request");
  39. }
  40. catch (Exception e)
  41. {
  42. logger.LogCritical(0, e, "Unexpected exception has occured");
  43. }
  44. }
  45. }
  46.  
  47. logger.LogInformation("Application terminated. Press <enter> to exit...");
  48. }
  49. else
  50. {
  51. Console.WriteLine("Application terminated. Press <enter> to exit...");
  52. }
  53.  
  54. Console.ReadLine();
  55. }
  56.  
  57. private static bool TryConfigureLogging(out ILoggerFactory loggerFactory, out ILogger logger)
  58. {
  59. loggerFactory = new LoggerFactory().AddConsole(LogLevel.Trace, true);
  60.  
  61. logger = loggerFactory.CreateLogger(typeof(Program));
  62.  
  63. try
  64. {
  65. logger.LogDebug("Configuring NLog");
  66.  
  67. loggerFactory
  68. .AddNLog()
  69. .ConfigureNLog(
  70. Path.Combine(Directory.GetCurrentDirectory(), "nlog.config"));
  71.  
  72. return true;
  73. }
  74. catch (Exception e)
  75. {
  76. logger.LogCritical(0, e, "Failed to configure application logging");
  77. loggerFactory = null;
  78. logger = null;
  79.  
  80. return false;
  81. }
  82. }
  83.  
  84. private static bool TryBuildConfigurations(ILogger logger, string[] args, out IConfigurationRoot configurationRoot)
  85. {
  86. logger.LogDebug("Building configurations");
  87.  
  88. try
  89. {
  90. var environmentName = Environment.GetEnvironmentVariable("ENVIRONMENT");
  91. if (string.IsNullOrWhiteSpace(environmentName))
  92. environmentName = "Production";
  93.  
  94. logger.LogDebug("Building configurations for '{environmentName}' environment", environmentName);
  95.  
  96. var configurationBuilder = new ConfigurationBuilder()
  97. .SetBasePath(Directory.GetCurrentDirectory())
  98. .AddJsonFile("appsettings.json", false, true)
  99. .AddJsonFile($"appsettings.{environmentName}.json", true, true)
  100. .AddEnvironmentVariables()
  101. .AddCommandLine(args);
  102.  
  103. configurationRoot = configurationBuilder.Build();
  104.  
  105. return true;
  106. }
  107. catch (Exception e)
  108. {
  109. logger.LogCritical(0, e, "Failed to build application configurations");
  110. configurationRoot = null;
  111.  
  112. return false;
  113. }
  114. }
  115.  
  116. private static bool TryBuildServiceProvider(
  117. ILogger logger, ILoggerFactory loggerFactory, IConfigurationRoot configurationRoot, out IServiceProvider serviceProvider)
  118. {
  119. logger.LogDebug("Building service provider");
  120.  
  121. try
  122. {
  123. var serviceCollection = new ServiceCollection()
  124. .AddSingleton(loggerFactory)
  125. .AddLogging()
  126. .AddSingleton(configurationRoot)
  127. .AddScoped<Application>();
  128.  
  129. serviceProvider = serviceCollection.BuildServiceProvider(true);
  130.  
  131. return true;
  132. }
  133. catch (Exception e)
  134. {
  135. logger.LogCritical(0, e, "Failed to build application service provider");
  136. serviceProvider = null;
  137.  
  138. return false;
  139. }
  140. }
  141.  
  142. public class Application
  143. {
  144. private readonly ILogger<Application> _logger;
  145.  
  146. public Application(ILogger<Application> logger)
  147. {
  148. _logger = logger;
  149. }
  150.  
  151. public Task RunAsync(CancellationToken ct)
  152. {
  153. _logger.LogInformation("Running the application logic");
  154.  
  155. return Task.CompletedTask;
  156. }
  157. }
  158. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement