I was working on a web application build on
Configuration in a console application
To use the configuration in console application several configuration providers packages need to be added. I am using the following packages:
- Microsoft.Extensions.Configuration.CommandLine
- Microsoft.Extensions.Configuration.EnvironmentVariables
- Microsoft.Extensions.Configuration.Json
Dependency injection in a console app
So it seems that is pretty easy to add Ms dependency injection in a console app. Two things need to be done:
- Add package: Microsoft.Extensions.DependencyInjection
- Use ServiceCollection to add dependencies and after to return the service provider. Create a method called RegisterServices please take a look below:
Logging in a console app
Again two steps are needed to use logging in a console app.
- Add package Microsoft.Extensions.Logging.Console
- Add inside RegisterServices method that was created for DI the line:
- serviceCollection.AddLogging(cfg => cfg.AddConsole());
RegisterServices should look now like this:
Putting all together
Add a new file called appsettings.json to test the that
{ "github":{ "apiUrl":"https://api.github.com/" } }
In the Main method we setup everything. Main should look like this:
If everything is set up correctly when running the application the following output should be displayed:
info: DI_Configuration_Logging_ConsoleApp.Program[0] Github api url is: https://api.github.com/
Github sample repository
All the code used here is available on github at https://github.com/emanuelpaul/DI-Configuration-Logging-ConsoleApp