We have covered many articles now about the generic host. The host is a concept encapsulates the dependency injection, configuration, logging and IHostedService implementations.
If you have gone through all the previous articles, this article might appear to be very obvious. I thought it might be good idea to demonstrate how to setup the host in console application, so that console application can use appsettings.json
configuration file.
Create Console App
Create a console application using dotnet
command line or visual studio. Once the application is created, add a reference to Microsoft.Extensions.Hosting nuget package. This package will provide all the necessary stuff
Add Json File
Add a json file, appsettings.json
, to the console application project. Notice that we have not made any code changes, so the file is not being read yet.
After adding the file, right click on appsettings.json and select properties. Then set “Copy to Ouptut Directory” option to Copy Always.
Add few settings to json file, so that you can verify that those settings are loaded.
Setup Host
Now, change the main method to create the host builder and then run it. The code is given below.
The code first creates the host builder and then applies the app configurations. The ConfigureAppConfiguration
method parameter, an Action
delegate, instructs the host to load configurations from appsettings.json
.
The code below does not load any settings from environment variables or from command line, but below example can be easily customized to meet application’s requirements.
Example Worker
This is just a demo class, where the IConfiguration is injected. Then in DoWork
method, we will print all the configuration values loaded in the application.
Below code shows the Program.cs
and Worker.cs
files.
Now when you run the code, you should be able to see all the configuration key value pairs loaded in the application.
I hope you find this information useful. Let me know your thoughts.