Skip to content

Instantly share code, notes, and snippets.

@gravity00
Last active September 23, 2017 17:32
Show Gist options
  • Select an option

  • Save gravity00/ef4163934ea883ca0becce7ad3de0369 to your computer and use it in GitHub Desktop.

Select an option

Save gravity00/ef4163934ea883ca0becce7ad3de0369 to your computer and use it in GitHub Desktop.
SimpleSoft.Hosting.WithBuilder
public static class Program
{
private static readonly CancellationTokenSource TokenSource;
static Program()
{
TokenSource = new CancellationTokenSource();
Console.CancelKeyPress += (sender, args) =>
{
TokenSource.Cancel();
args.Cancel = true;
};
}
public static int Main(string[] args) =>
MainAsync(args, TokenSource.Token).ConfigureAwait(false).GetAwaiter().GetResult();
private static async Task<int> MainAsync(string[] args, CancellationToken ct)
{
int resultCode;
var loggerFactory = new LoggerFactory().AddConsole(LogLevel.Trace, true);
var logger = loggerFactory.CreateLogger(typeof(Program));
logger.LogInformation("Application started...");
try
{
using (var hostBuilder = new HostBuilder("ENVIRONMENT")
.UseLoggerFactory(loggerFactory)
.ConfigureConfigurationBuilder(p =>
{
p.Builder
.SetBasePath(p.Environment.ContentRootPath)
.AddJsonFile("appsettings.json", false, true)
.AddJsonFile($"appsettings.{p.Environment.Name}.json", true, true)
.AddEnvironmentVariables()
.AddCommandLine(args);
})
.ConfigureLoggerFactory(p =>
{
p.LoggerFactory
.AddNLog()
.ConfigureNLog(
p.Environment.ContentRootFileProvider.GetFileInfo("nlog.config").PhysicalPath);
})
.ConfigureServiceCollection(p =>
{
// nothing to be done here for the example because
// ILoggerFactory, IConfigurationRoot, IHostingEnvironment are automaticaly registered
})
.UseServiceProviderBuilder(p =>
{
// also not needed. This is the implementation by default
return p.ServiceCollection.BuildServiceProvider(true);
}))
{
await hostBuilder.RunHostAsync<Application>(ct).ConfigureAwait(false);
}
resultCode = 0;
}
catch (TaskCanceledException)
{
logger.LogWarning("The application execution was canceled by request");
resultCode = 2;
}
catch (Exception e)
{
logger.LogCritical(0, e, "Unexpected exception has occured");
resultCode = 1;
}
logger.LogInformation("Application terminated. Press <enter> to exit...");
Console.ReadLine();
return resultCode;
}
public class Application : IHost
{
private readonly ILogger<Application> _logger;
public Application(ILogger<Application> logger)
{
_logger = logger;
}
public Task RunAsync(CancellationToken ct)
{
_logger.LogInformation("Running the application logic");
return Task.CompletedTask;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment