Console app with configuration, dependency injection and logging

I was working on a web application build on .NET core that is using the built-in dependency injection, configuration, and logging. Some functionality needs to be shared in both this web app and also in a console application. The services project used in the web app having this functionality was already using Microsoft extensions logging. To use in the console app the logging functionality and to resolve the dependencies from the services project the simplest way is to use Microsoft extensions logging(asp.net core DI). For simplicity reasons, all the setup from the following examples is done in Program.cs

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

Also configuration needs to be setup but it is pretty easy. Please take a look below:

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. First step is to add the logging providers and the second is to make the setup. For simplicity, I am adding only the console logging provider but any provider can be added like for example the excellent Serilog provider.

  • 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 json config providers are working fine. In the file add the following:

 {
    "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