.net Core Read Appsettings.json From Test Project
We have covered many manufactures at present nearly the generic host. The host is a concept encapsulates the dependency injection, configuration, logging and IHostedService implementations.
If you lot accept gone through all the previous articles, this article might appear to be very obvious. I thought information technology might be skillful idea to demonstrate how to setup the host in console application, so that console application can use appsettings.json
configuration file.
Create Panel App
Create a console awarding using dotnet
command line or visual studio. Once the application is created, add a reference to Microsoft.Extensions.Hosting nuget bundle. This package volition provide all the necessary stuff
Add Json File
Add a json file, appsettings.json
, to the panel application project. Notice that nosotros accept non fabricated any lawmaking changes, so the file is not beingness read yet.
Afterwards calculation the file, correct click on appsettings.json and select properties. Then prepare "Copy to Ouptut Directory" choice to Re-create Always.
Add together few settings to json file, then that yous tin can verify that those settings are loaded.
Setup Host
Now, alter the master method to create the host builder and then run it. The code is given below.
The code get-go creates the host builder and then applies the app configurations. The ConfigureAppConfiguration
method parameter, an Action
consul, instructs the host to load configurations from appsettings.json
.
The code below does not load whatsoever settings from environs variables or from command line, but below case tin be hands customized to run into application'southward requirements.
Example Worker
This is just a demo grade, where the IConfiguration is injected. Then in DoWork
method, we volition print all the configuration values loaded in the application.
Beneath code shows the Program.cs
and Worker.cs
files.
Now when y'all run the code, you lot should be able to encounter all the configuration key value pairs loaded in the application.
I hope you lot find this data useful. Permit me know your thoughts.
Source: https://thecodeblogger.com/2021/05/04/how-to-use-appsettings-json-config-file-with-net-console-applications/
0 Response to ".net Core Read Appsettings.json From Test Project"
Post a Comment