Skip to content

Library to simplify the hosting of console applications by making it easier to setup dependency injection, logging and configurations

License

Notifications You must be signed in to change notification settings

simplesoft-pt/Hosting

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

74 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Hosting

Library to simplify the hosting of console applications by making it easier to setup dependency injection, logging and configurations.

Installation

The library is available via NuGet packages:

NuGet Description Version
SimpleSoft.Hosting.Abstractions interfaces and abstract implementations (IHost, IHostBuilder, ...) NuGet
SimpleSoft.Hosting library implementation that typically is only known by the main project NuGet

Package Manager

Install-Package SimpleSoft.Hosting.Abstractions
Install-Package SimpleSoft.Hosting

.NET CLI

dotnet add package SimpleSoft.Hosting.Abstractions
dotnet add package SimpleSoft.Hosting

Packet CLI

paket add package SimpleSoft.Hosting.Abstractions
paket add package SimpleSoft.Hosting

Compatibility

This library is compatible with the following frameworks:

  • SimpleSoft.Hosting.Abstractions
    • .NET Standard 1.1;
  • SimpleSoft.Hosting
    • .NET Framework 4.5.1;
    • .NET Standard 1.3;
    • .NET Standard 1.5;

Usage

Documentation is available via wiki or you can check the working examples or test code.

Here is an example of a console application:

public class Program
{
    private static readonly CancellationTokenSource TokenSource;

    static Program()
    {
        TokenSource = new CancellationTokenSource();
        Console.CancelKeyPress += (sender, eventArgs) =>
        {
            TokenSource.Cancel();
            eventArgs.Cancel = true;
        };
    }

    public static void Main(string[] args) =>
        MainAsync(args, TokenSource.Token).ConfigureAwait(false).GetAwaiter().GetResult();

    private static async Task MainAsync(string[] args, CancellationToken ct)
    {
        var loggerFactory = new LoggerFactory()
            .AddConsole(LogLevel.Trace, true);

        var logger = loggerFactory.CreateLogger<Program>();

        logger.LogInformation("Application started");
        try
        {
            using (var hostBuilder = new HostBuilder("ASPNETCORE_ENVIRONMENT")
                .UseLoggerFactory(loggerFactory)
                .UseStartup<Startup>()
                .ConfigureConfigurationBuilder(p => p.Builder.AddCommandLine(args)))
            {
                await hostBuilder.RunHostAsync<Host>(ct);
            }
        }
        catch (TaskCanceledException)
        {
            logger.LogWarning("Application was terminated by user request");
        }
        catch (Exception e)
        {
            logger.LogCritical(0, e, "Unexpected exception");
        }
        finally
        {
            logger.LogInformation("Application terminated. Press <enter> to exit...");
            Console.ReadLine();
        }
    }

    private class Startup : HostStartup
    {
        public override void ConfigureConfigurationBuilder(IConfigurationBuilderParam param)
        {
            param.Builder
                .SetBasePath(param.Environment.ContentRootPath)
                .AddJsonFile("appsettings.json", true, true)
                .AddJsonFile($"appsettings.{param.Environment.Name}.json", true, true)
                .AddEnvironmentVariables();
        }

        public override IServiceProvider BuildServiceProvider(IServiceProviderBuilderParam param)
        {
            var container = new Autofac.ContainerBuilder();
            container.Populate(param.ServiceCollection);
            return new AutofacServiceProvider(container.Build());
        }
    }

    private class Host : IHost
    {
        private readonly IHostingEnvironment _env;
        private readonly IConfigurationRoot _configurationRoot;
        private readonly ILogger<Host> _logger;

        public Host(IHostingEnvironment env, IConfigurationRoot configurationRoot, ILogger<Host> logger)
        {
            _env = env;
            _configurationRoot = configurationRoot;
            _logger = logger;
        }

        public Task RunAsync(CancellationToken ct)
        {
            _logger.LogDebug("Running host...");

            return Task.CompletedTask;
        }
    }
}

About

Library to simplify the hosting of console applications by making it easier to setup dependency injection, logging and configurations

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published