.net core tutorials

How to use Configuration API in .net core console application

One of the most common applications in .net I end up developing is Console Applications. They are by far the most useful applications any developer can develop to and their usage expands far further than writing text out to a terminal window. For instance, they are essentially the basis for developing Linux Daemons or if you’re using TopShelf – An easy service hosting framework for building Windows services using .NET. , you can quickly and easily build Windows Service applications.

Using the new Console application template that ships with the .net core, generates a really stripped down basic application with the absolute minimum references required for an application. This leads to some confusion amongst developers as to what references they need to import to get the same features which are common amongst the other application generation templates.

In this post, I will walk you through the steps involved to make use of JSON Application settings file to store and retrieve application configuration settings in a .net core console application.

Code available on Github

Background

The life of a Freelance Full Stack Software Developer is one of constantly opening and editing a number of different code bases initially developed by others in order to patch bugs, add features, enhance existing features or rather more than I care to admit find out WTF is going on with an existing application.

I recently had one of those WTF assignments, when a client reported that a daemon that has been used to process a critical data manipulation workload for their application had recently stopped working and nobody could figure out why, in many ways, this is like being a Digital Crime Scene Investigator.

The daemon had been developed using .net core, but they didn’t have the resource available who had experience in order to troubleshoot. Fortunately, they had the source code and asked if I could figure what was wrong.

After 30 minutes of studying the code base, I was able to uncover the root of the problem. The previous developer had implemented a custom environment configuration file handler. I was able to work out that they were trying to do. Which is something fairly common in Docker-compose, Python, PHP and JavaScript, known as .env files – which are a means declaring default environment variables in an environment file named .env placed in the folder where a command is executed.  Commonly referred to as Configuration files.

The downside to the previous developers Custom Configuration file implementation is that they had over 100 SLOC (Source Lines Of Code) of implementation logic, just to basically read a Database Connection string from the environment file.

I fully understand what they attempted to do, but what I could figure out was why? The wheel existed, well used, trusted and scalable why did they need to re-invent it? Especially when the entire daemon they developed only 150 SLOC.  

It is common knowledge within software development, that the more lines of code you write it increases the likelihood of bugs creeping in, and this example this is exactly what happened.   The custom file configuration handler had become the root problem for the bug  to occur.

Featured Book Review


Configuration API in ASP.NET Core

The .NET core framework comes with comprehensive Configuration API which provides a mechanism to configure a .NET Core application based on a list of name-value pairs.

This enables Configuration data to be read at runtime from multiple sources, using Name-value pairs which can be grouped into a multi-level hierarchy.

There are configuration providers for:

  • File formats (INI, JSON, and XML )
  • Command-line arguments
  • Environment variables
  • In-memory .NET objects
  • Unencrypted Secret Manager storage
  • Encrypted user store, such as Azure Key Vault
  • Custom providers

The configuration API really simplifies using configuration files and comes with some really good features.

 



Generate a console application in .net core

I thought I would have a bit of fun and implement a trivial Console Application in .Net core to walk through the process of using Configuration API. The application itself is just the Simple FizzBuzz algorithm and the Configuration aspect of the application enables the configuration of string values for Fizz and Buzz to be replaced by a string of choice by system configuration.

How to create console application in .net core

I usually develop .net core applications on Ubuntu and predominantly use Visual Studio Code, therefore I will use mostly the terminal window commands to generate the application.

To generate a console application in .net core we’ll use the dotnet new <application type> command a with a  couple of option switches

This command will generate the basic structure of the application and will have just enough to run the application but nothing else.  Let’s look at the structure of the project file:

We have basically got a reference to the Target Framework and that is about it.  There have been no other dependencies added.

Taking a look at Program.cs file we’ll see that the only thing the application can do at this point is print out “Hello World!” to the terminal.

 

How to run .net Core console app from the command line

It possible to Pass arguments to a console application when running it from a command line.  If we alter the code

We can now create application stubs with the command dotnet build and then change into the directory cd bin/Debug//netcoreapp2.0/ we can now execute the application using the command dotnet FizzBuzz "Gary" and we should see the following result

This works great if you want to pass in additional arguments to a Console application, for instance, we could configure our simple Console application to run as a Linux daemon, by creating what is commonly called systemd user units.

 

Branch on Github



Adding a Reference to the Configuration API

In order to enable our Console Application to read Configuration from files we will need to add a reference to the following libraries

  • Microsoft.Extensions.Configuration – enables key-value pair based configurations
  • Microsoft.Extensions.Configuration.FileExtensions – Extension methods for configuring file-based configuration providers
  • Microsoft.Extensions.Configuration.Json – JSON configuration provider

Once the references have been added simply do a dotnet restore to ensure they are added to your project.

Create a simple appsettings.json to store our configuration settings. For the purpose of demonstration lets add the file with the following code:

Edit the .csproj file and add the following lines to the file.

These lines will ensure that the appsettings.json file will be copied to the  Output Directory property. To ensure we copy the most up to date version of the file set it toPreserveNewest

We have ensured that the configuration file into the working directory, we can just refer to it by name without providing a directory path.

We now need to import the 3 libraries we referenced to our Console Application.

Once they are referenced we can now utilise them in our application.  We’ll slightly ammend our Main method to read our new appsettings.json file.

Once this has been done we can now now simplistically read the contents of our config file. Lets update the Console.WriteLine to write the name that is stored in our Configuration File.

Your app settings file will look like this

We are now able to access the data stored in our json file via a name-value key pairing

The completed code should look as follows

Running the application we will get to see the following printed out to the command line

This works great for really simple Configuration Options and really simple applications. However, if we start getting into more complex applications and we want to split our configuration options up into sections with strongly typed access, that we will ideally use for different sections of the application. We can easily extend up this option.

Branch on Github



Using Strongly typed configuration in .net core console application

The features highlighted above illustrate how easy and flexible it can be to use Configuration API in a .net core console applications. However, you may be thinking it’s a little clunky and there is a little danger of overuse of Magic Strings and make your code a little verbose.

Ideally you would want to make use of Strongly typed configuration serialised classes. In order to do this we will need to make use of Depenedency Injection. In order to do so we need to add an additional reference

  • Microsoft.Extensions.Configuration.Binder

We now create a couple of additional classes, one for our Application settings and another to for the actual App we’re going to run.

We can now serialis the class, using the Get method of the Binder extensions.

Branch on Github



Summary

In this post we covered the basic of how to use Configuration API in a .net core console application to store and retrieve Application Configuration data.

This dramatically simplifies your approach. However this is still not the optimum approach and in a forthcoming post we will look at using strongly typed configuration in .NET Core console application but before that we will need to discuss Dependency Injection in .net core.

Gary Woodfine

Freelance Full Stack Developer at threenine.co.uk
Helps businesses by improving their technical proficiencies and eliminating waste from the software development pipelines.

A unique background as business owner, marketing, software development and business development ensures that he can offer the optimum business consultancy services across a wide spectrum of business challenges.

Latest posts by Gary Woodfine (see all)

Affiliate Disclaimer

Disclosure: Please note that some of the links included in the blog posts are affiliate links, which means I will earn a commission if you decide to make a purchase.

I only include affiliate links to products, services and companies that I have personal experience and have actually used. I only recommend them because they are helpful and useful, not because of the small commissions I make if you decide to buy something.

Please do not spend any money on these products unless you feel they are relevant, suitable and will help you achieve your goals.

Buying anyone of these products and the commisions earned will not make me an overnite multi millionaire, but they will help to cover the hosting costs and compensate for the countless hours and effort I put in to create meaningful and valuable free content I provide to help others succeed.

You've also undoubtedly noticed that I also use various advertising networks - unless of of course you're using an Ad blocker, this is also an attempt to reduce my monthly deficit I experience in providing free relevant, valuable and on occassion insightful content for the benefit of others.

I only really make some money if people click on the ads, unless of course you consider 1c per 1000 impressions real money!

Bear in mind just how many impressions I need to make before I can cover my £20 hosting costs a month!

If you are using an adblocker and guilt stricken you can of course donate using any of the buttons below, but I won't be holding my breath.


Buy me a coffeeBuy me a coffee
π