A Coder's Blog
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.
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”
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)
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.
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
Running the app I can see my config setting printed in console.