A .net core console application is an amazing bare bones application template which lets you quickly test out ideas. At the same time it can also be used to build a production ready application. Since it is a light weight application template it does not have functionality such as dependency injection baked in.
As a .net core console application does not have dependency injection built in, features that an application generally depends on such as configuration is not readily available. In a full fledged ASP.net core application , configuration is available using the injected IConfiguration interface by default. In a .Net core console application Configuration can be added using the ConfigurationBuilder class. Additionally support for configuring the application using a Json file, environmental variables, command line or using a custom configuration provider can also be added.
The IConfiguration and the Configuration builder types are available in the Microsoft.Extensions.Configuration package. The extensions to add a json file such as appsettings.json as a configuration source is available in the Microsoft.Extensions.Configuration.Json nuget package. The extensions to add Environmental variables as a configuration source is available in the nuget package Microsoft.Extensions.Configuration.EnvironmentVariables. the extensions to add the command line as a configuration source is available in the Microsoft.Extensions.Configuration.CommandLine nuget package.
The above nuget packages can be installed using the install-package command as below.
Once these packages are installed it provides the necessary functionality to use the ConfigurationBuilder class. In the below gist i am adding a json configuration file called appsettings.json. I am also adding environmental variables and command line as a configuration source.
Now that we have built our configuration providers we can use them as below
Each configuration source overrides the configuration source in the order in which it is has been added to the configuration builder. The Sections can also assigned to strongly typed objects representing the configuration using the Bind method.
In the next post let us take a look at implementing Dependency injection in a console application.