The most common .net core applications I end up developing are Console Applications. They are by far the most useful applications any developer can develop and their usage expands far further than simply 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 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 a JSON Application settings file to store and retrieve application configuration settings in a .net core console application.
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 which had been used to process a critical data manipulation workload for their application 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 with experience with .net core to troubleshoot. Fortunately, they did have the source code and asked if I could figure what was wrong.
.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 couldn’t 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 had 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 cause of the bug.
Configuration API in ASP.NET Core
The .NET core framework comes with a comprehensive Configuration API which provides a mechanism to configure a .NET Core application based on a list
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 Rider, therefore I generally use 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 generates the basic structure of an application and has just enough code to run the application but nothing else.
Let’s look at the structure of the project file:
As you can tell there is basically a reference to the
Target Framework and that is about it. No other dependencies have been 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
Its possible to Pass arguments to a console application when running it from a command line. If we alter the code slightly to use any arguments passed in
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.
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, we can 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 this demonstration lets add the file with the following code:
.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 to
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
Once this has been done we can now now simply 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 application scenarios 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.
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.
To learn more about minimising the use of Magic Strings and Numbers within your code, I recommend reading Java By Comparison: Become a Java Craftsman in 70 Examples. Although the book is mostly about Java, you’ll find that many of the suggestions pertain just as much to C#
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 achieve this we will nee to add an additional reference, to the
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 serialise the class, using the
Get method of the Binder extensions. In order to do lets create a class with a some properties that we would like populated. Lets create a Hello class with a name property.
We can then edit out AppSettings file adding the section that looks something like this
We can then bind the information in the following manner.
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.
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)
- The Builder Pattern .net core - May 1, 2019
- Book Review: The Lean Startup - April 28, 2019
- Using Serverless Framework Environment Variables .net core Lambda - April 25, 2019