ma.citi

A Coder's Blog

Configuration in .NET Core 2.2 Console App using HostBuilder

Similar to the WebHostBuilder class that allows to build a WebHost which hosts a web application, since .Net core 2.1, for non http scenarios, a generic HostBuilder has been available, and allows us to build an Host (IHost) that hosts services.

In my previous post Configuration in .NET Core 1.0 Console Application I described how to load application settings from a json file in a console app written in .net core 1.0.

In this post, using .Net core 2.2, I tried to do the same using the HostBuilder.

Add an AppSettings.json file

After a Console App (.Net Core > 2.1) is created, add a json file. I called it appsettings.json. Add some key/values and in its properties select “Copy if newer” for “Copy to Output Directory”

app settings

app settings

The HostBuilder

Using nuget I installed the following packages:

I created a class in order to bind my configuration section against an object (note that property names must match config names)

    public class RabbitMqConfiguration
    {
        public string Uri { get; set; }

        public string VirtualHost { get; set; }

        public string User { get; set; }

        public string Password { get; set; }
	
    }

I will use the HostBuilder to build an Host (IHost). In Main using the ConfigureAppConfiguration method of the HostBuilder I’ll set up the configuration, and using the ConfigureServices method I’ll add services to the app’s dependency injection container.

In the ConfigurationServices method I registered a configuration instance where I bound the RabbitMq configuration section against the RabbitMqConfiguration class. I also registered a hosted service.

	public static async Task Main(string[] args)
	{
		var host = new HostBuilder().ConfigureAppConfiguration((hostContext, configApp) =>
		{
			configApp.AddJsonFile("appsettings.json", optional: true);
		})
		.ConfigureServices((hostContext, services) =>
		{
			services.Configure<RabbitMqConfiguration>(hostContext.Configuration.GetSection("RabbitMq"));
			services.AddHostedService<TestService>();
		})
		.Build();

		await host.RunAsync();
	}

The Hosted Service

The idea is that the hosted service is a background task hosted in the service container. The hosted service has to implement the IHostedService interface, implementing StartAsync and StopAsync methods.

the host is responsible to start and stop all the services that are registered in the service container.

I created a simple service that prints in console a config value. The service receives the configuration object once is created through dependency injection. note: check the option pattern pattern

    public class TestService : IHostedService
    {
        private readonly RabbitMqConfiguration _rabbitConfiguration;

        public TestService(IOptions<RabbitMqConfiguration> options)
        {
            _rabbitConfiguration = options.Value;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            await Console.Out.WriteLineAsync("starting service..");
            await Console.Out.WriteLineAsync($"config user value: {_rabbitConfiguration.User}");
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            await Console.Out.WriteLineAsync("stopping service..");
        }
    }

Running the app I can see my config setting printed in console.