64  
dotnet
Поиск  
Always will be ready notify the world about expectations as easy as possible: job change page
Jul 5

Building a console app with .NET Generic Host

Building a console app with .NET Generic Host
Автор:
Источник:
Просмотров:
138

The .NET Generic Host is a feature which sets up some convenient patterns for an application including those for dependency injection (DI), logging, and configuration. It was originally named Web Host and intended for Web scenarios like ASP.NET Core applications but has since been generalized (hence the rename to Generic Host) to support other scenarios, such as Windows services, Linux daemon services, or even a console app.

A working example can be found at dfederm/GenericHostConsoleApp.

Basics

You will first need to create a new console application and add a PackageReference to Microsoft.Extensions.Hosting.

dotnet new console
dotnet add package Microsoft.Extensions.Hosting

Now for the Main method. Typically the Main method for console apps just immediately jump into the application’s core logic, but when using the .NET Generic Host, instead the host is set up. This should look familiar if you’ve developed web applications using the Web Host or Generic Host before.

internal sealed class Program
{
    private static async Task Main(string[] args)
    {
        await Host.CreateDefaultBuilder(args)
            .RunConsoleAsync();
    }
}

Running that alone will start up the host, but without any logic it will do nothing and never exit. The generic host simply sets up some reasonable defaults around configuration and logging, as well as provides a few services in the DI container which handle the the application lifetime. Calling RunConsoleAsync will run start the host and wait for a Ctrl+C or SIGTERM to exit, which means without explicitly telling the app to exit, it will not exit.

To actually implement your console app’s logic, and get the application to exit after it’s done, you’ll want to implement and register an IHostedService, as well as interact with the IHostApplicationLifetime from the DI container.

internal sealed class Program
{
    private static async Task Main(string[] args)
    {
        await Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<ConsoleHostedService>();
            })
            .RunConsoleAsync();
    }
}

internal sealed class ConsoleHostedService : IHostedService
{
    private readonly ILogger _logger;
    private readonly IHostApplicationLifetime _appLifetime;

    public ConsoleHostedService(
        ILogger<ConsoleHostedService> logger,
        IHostApplicationLifetime appLifetime)
    {
        _logger = logger;
        _appLifetime = appLifetime;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogDebug($"Starting with arguments: {string.Join(" ", Environment.GetCommandLineArgs())}");

        _appLifetime.ApplicationStarted.Register(() =>
        {
            Task.Run(async () =>
            {
                try
                {
                    _logger.LogInformation("Hello World!");

                    // Simulate real work is being done
                    await Task.Delay(1000);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Unhandled exception!");
                }
                finally
                {
                    // Stop the application once the work is done
                    _appLifetime.StopApplication();
                }
            });
        });

        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }
}

Other useful events to subscribe to on the IHostApplicationLifetime are ApplicationStopping and ApplicationStopped.

Note that you can registrer multiple IHostedService implementations and each of them will have their StartAsync and StopAsync methods called. However, personally I find that to be a bit confusing for a console application, so I would just stick to a single IHostedService.

Dependency Injection

As you may have noticed, your IHostedService implementation has full access to the DI container, so you can register services in Main and then use them in your IHostedService.

In Main:

await Host.CreateDefaultBuilder(args)
    .ConfigureServices((hostContext, services) =>
    {
        services
            .AddHostedService<ConsoleHostedService>();
            .AddSingleton<IWeatherService, WeatherService>();
    })
    .RunConsoleAsync();

In ConsoleHostedService:

private readonly ILogger _logger;
private readonly IHostApplicationLifetime _appLifetime;
private readonly IWeatherService _weatherService;

public ConsoleHostedService(
    ILogger<ConsoleHostedService> logger,
    IHostApplicationLifetime appLifetime,
    IWeatherService weatherService)
{
    _logger = logger;
    _appLifetime = appLifetime;
    _weatherService = weatherService;
}

public Task StartAsync(CancellationToken cancellationToken)
{
    _appLifetime.ApplicationStarted.Register(() =>
    {
        Task.Run(async () =>
        {
            try
            {
                IReadOnlyList<int> temperatures = await _weatherService.GetFiveDayTemperaturesAsync();
                for (int i = 0; i < temperatures.Count; i++)
                {
                    _logger.LogInformation($"{DateTime.Today.AddDays(i).DayOfWeek}: {temperatures[i]}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Unhandled exception!");
            }
            finally
            {
                // Stop the application once the work is done
                _appLifetime.StopApplication();
            }
        });
    });

    return Task.CompletedTask;
}

Exit Code

To return a non-zero exit code, your IHostedService implementation can set Environment.ExitCode when the host is stopping.

internal sealed class ConsoleHostedService : IHostedService
{
    private int? _exitCode;

    // ...

    public Task StartAsync(CancellationToken cancellationToken)
    {
        // ...

        _appLifetime.ApplicationStarted.Register(() =>
        {
            Task.Run(async () =>
            {
                try
                {
                    // ...

                    _exitCode = 0;
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Unhandled exception!");
                    _exitCode = 1;
                }
                finally
                {
                    // Stop the application once the work is done
                    _appLifetime.StopApplication();
                }
            });
        });

        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogDebug($"Exiting with return code: {_exitCode}");

        // Exit code may be null if the user cancelled via Ctrl+C/SIGTERM
        Environment.ExitCode = _exitCode.GetValueOrDefault(-1);
        return Task.CompletedTask;
    }
}

Logging and Configuration

Logging and configuration work mostly just as they do in Web applications. The one caveat is that because appsettings.json is loaded from the content root, which for the Generic Host is the current working directory by default, the content root needs to be set to the same directly the executable is in using UseContentRoot.

In Main:

await Host.CreateDefaultBuilder(args)
    .UseContentRoot(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))
    .ConfigureLogging(logging =>
    {
        // Add any 3rd party loggers like NLog or Serilog
    })
    .ConfigureServices((hostContext, services) =>
    {
        services
            .AddHostedService<ConsoleHostedService>()
            .AddSingleton<IWeatherService, WeatherService>();

        services.AddOptions<WeatherSettings>().Bind(hostContext.Configuration.GetSection("Weather"));
    })
    .RunConsoleAsync();

In WeatherService.cs:

internal sealed class WeatherService : IWeatherService
{
    private readonly IOptions<WeatherSettings> _weatherSettings;

    public WeatherService(IOptions<WeatherSettings> weatherSettings)
    {
        _weatherSettings = weatherSettings;
    }

    public Task<IReadOnlyList<int>> GetFiveDayTemperaturesAsync()
    {
        int[] temperatures = new[] { 76, 76, 77, 79, 78 };
        if (_weatherSettings.Value.Unit.Equals("C", StringComparison.OrdinalIgnoreCase))
        {
            for (int i = 0; i < temperatures.Length; i++)
            {
                temperatures[i] = (int)Math.Round((temperatures[i] - 32) / 1.8);
            }
        }

        return Task.FromResult<IReadOnlyList<int>>(temperatures);
    }
}

In WeatherSettings.cs:

internal sealed class WeatherSettings
{
    public string Unit { get; set; }
}

In the project file:

<ItemGroup>
    <Content Include="appsettings.json">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>
</ItemGroup>

In appsettings.json:

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            // Avoid logging lifetime events
            "Microsoft.Hosting.Lifetime": "Warning"
        }
    },
    "Weather": {
        "Unit": "C"
    }
}
Похожее
May 30
Author: Erik Pourali
Imagine crafting a library app where users effortlessly find books by title, author, or genre. Traditional search methods drown you in code. But fear not! Dynamic Querying in C# saves the day. In our tale, crafting separate search methods for...
Jun 6
Author: Dayanand Thombare
The Deadlock Dilemma 🔒 In the world of multithreaded programming, deadlocks lurk like silent assassins, waiting to strike when you least expect it. A deadlock occurs when two or more threads become entangled in a vicious cycle, each holding a...
May 6
Author: Sasha Marfut
Clean Architecture in practice. Clean Architecture is a popular approach to building software applications. A Clean Architecture defines clear boundaries between different application layers, resulting in improved maintainability. In addition, Clean Architecture approach aims to keep the business logic independent...
Apr 7, 2023
Author: Matt Eland
Exploring nullability improvements in C# and the !, ?, ??, and ??= operators. Null is famously quoted as being the "billion-dollar mistake" due to the quantity of NullReferenceExceptions that we see in code (particularly when just starting out). The prevalence...
Написать сообщение
Почта
Имя
*Сообщение


© 1999–2024 WebDynamics
1980–... Sergey Drozdov
Area of interests: .NET Framework | .NET Core | C# | ASP.NET | Windows Forms | WPF | HTML5 | CSS3 | jQuery | AJAX | Angular | React | MS SQL Server | Transact-SQL | ADO.NET | Entity Framework | IIS | OOP | OOA | OOD | WCF | WPF | MSMQ | MVC | MVP | MVVM | Design Patterns | Enterprise Architecture | Scrum | Kanban