Init
This commit is contained in:
58
Program.cs
Normal file
58
Program.cs
Normal file
@ -0,0 +1,58 @@
|
||||
using File_Watcher.Models;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.Hosting.WindowsServices;
|
||||
|
||||
namespace File_Watcher;
|
||||
|
||||
public class Program
|
||||
{
|
||||
|
||||
internal static async Task Main(string[] args)
|
||||
{
|
||||
ILogger<Program>? logger = null;
|
||||
#pragma warning disable IL3050
|
||||
WebApplicationBuilder webApplicationBuilder = WebApplication.CreateBuilder(args);
|
||||
#pragma warning restore IL3050
|
||||
_ = webApplicationBuilder.Configuration.AddUserSecrets<Program>();
|
||||
AppSettings appSettings = Models.Binder.AppSettings.Get(webApplicationBuilder.Configuration);
|
||||
if (string.IsNullOrEmpty(appSettings.Company))
|
||||
throw new Exception("Company name must have a value!");
|
||||
try
|
||||
{
|
||||
List<string> collection = new();
|
||||
_ = webApplicationBuilder.Services.AddHostedService<Worker>();
|
||||
_ = webApplicationBuilder.Services.AddSingleton(collection);
|
||||
_ = webApplicationBuilder.Services.AddSingleton(appSettings);
|
||||
if (WindowsServiceHelpers.IsWindowsService())
|
||||
{
|
||||
collection.Add(nameof(WindowsServiceLifetime));
|
||||
_ = webApplicationBuilder.Services.AddSingleton<IHostLifetime, WindowsServiceLifetime>();
|
||||
_ = webApplicationBuilder.Logging.AddEventLog(settings =>
|
||||
{
|
||||
#pragma warning disable CA1416
|
||||
if (string.IsNullOrEmpty(settings.SourceName))
|
||||
settings.SourceName = webApplicationBuilder.Environment.ApplicationName;
|
||||
#pragma warning restore
|
||||
});
|
||||
}
|
||||
using IHost host = webApplicationBuilder.Build();
|
||||
logger = host.Services.GetRequiredService<ILogger<Program>>();
|
||||
if (string.IsNullOrEmpty(appSettings.Company))
|
||||
{
|
||||
Environment.ExitCode = -1;
|
||||
_ = host.StopAsync();
|
||||
}
|
||||
logger.LogInformation("Starting Web Application");
|
||||
logger.LogCritical("{Company}", appSettings.Company);
|
||||
await host.RunAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try
|
||||
{ logger?.LogCritical(ex, "Host terminated unexpectedly"); }
|
||||
catch (Exception) { }
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user