Using Config.Net for .NET Application Configurations
A while back I wrote an article detailing how to create custom configuration sections in the App.config file in .NET. This is by far the most...
A while back I wrote an article describing how to create custom configuration sections in the App.config file in .NET. This is by far the most popular blog post I have posted on this website as it has consistently outperformed all of my other posts:
I decided to write this follow-up post describing how you can use Config.Net for configurations in your .NET (and .NET Core) applications for a few reasons:
- It works with .NET Core
With .NET Core, Microsoft moved configuration for applications to the appsettings.json file instead of an XML-based App.config file. This means that the App.config approach described in the old article will not work in .NET Core. However Config.Net is a .NET Standard library meaning it works in both .NET Core and .NET Framework so what you learn here can apply to both! - It supports many different configuration forms
Config.Net can access configuration settings stored in different file formats using the same API. This makes it incredible simple to change our configuration file format without having to rewrite a whole bunch of code. It also makes it Dependency Injection friendly! - Very little boilerplate code
Unlike our custom App.config configuration sections, Config.Net requires very little boilerplate to work. No more writing custom classes that inherit fromConfigurationElement
,ConfigurationElementArray
, etc. You literally just define interfaces to match your configuration file structure and you're good to go! - Write to configuration files
You also have the option to optionally write back to the configuration file (if the configuration provider supports it). This makes it useful for when you want to allow the user to change some settings in the application and not have to dig in the configuration file.
There are a lot more benefits I could go through as it's very well-written. There are also other configuration libraries available that we could use, however, unless you are developing an ASP.NET Core Web Application or something that already has its own configuration library baked in, I have found Config.Net to be the easiest to get started with and maintain.
Installing
Base Library
The first step is to install the base Nuget package. This contains all the code that is common between the different configuration formats. You can install it using either one of the following commands depending on your environment:
Package Manager
Install-Package Config.Net
.NET CLI
dotnet add package Config.Net
The base library has a few configuration providers builtin. You'll find the following providers:
- App.Config
- Assembly Config
- Azure DevOps Variable Set
- Command Line Arguments
- Environment Variables
- In-Memory Dictionary
- INI File
- INI String
Additional Configuration Provider Libraries
There are some additional configuration provider library that you can also install if the format you need is not supported in the base library (e.g. JSON):
- Config.Net.Json - Adds support for JSON configuration files
- Config.Net.Azure.KeyVault - Adds support for Azure Key Vault
- Config.Net.Yaml - Adds support for YAML configuration files
Once you've installed the Configuration Provider Library that you want to use, you can use the appropriate extension method to configure it (see below).
Our sample configuration file (JSON)
For this article, we will be basing our configuration code on this appsettings.json file. This is just to give an overview of using the Config.Net library. You can very easily change your configuration provider and still follow along.
{
"Application": {
"AllowBetaFunctionality": false,
"Version": "1.0.0",
"Support": {
"Name": "Ivan Kahl",
"Email": "[email protected]",
"Phone": "030-555-3233"
}
},
"Theme": {
"Primary": "#e02834",
"Secondary": "#2d2d2d"
}
}
Make sure that you create your appsettings.json file in the root of your project and set Copy to Output Directory to Copy if newer:
Defining your configuration interfaces
This first thing you need to do is define the structure of your configuration file using interfaces. These interfaces will provide us with a structured method of accessing our configuration file.
Let's define the interfaces to match our configuration file above. To keep my code clean, I am creating a Configuration folder in my project where I will store all these interfaces.
IAppSettings.cs
namespace ConfigNetTutorial.Configuration
{
public interface IAppSettings
{
IApplicationSettings Application { get; set; }
IThemeSettings Theme { get; set; }
}
}
IApplicationSettings.cs
namespace ConfigNetTutorial.Configuration
{
public interface IApplicationSettings
{
bool AllowBetaFunctionality { get; set; }
// We don't want to let the program update these
// so we only specify getters for these properties
string Version { get; }
ISupportSettings Support { get; }
}
}
ISupportSettings.cs
namespace ConfigNetTutorial.Configuration
{
public interface ISupportSettings
{
string Name { get; }
string Email { get; }
string Phone { get; }
}
}
IThemeSettings.cs
namespace ConfigNetTutorial.Configuration
{
public interface IThemeSettings
{
string Primary { get; set; }
string Secondary { get; set; }
}
}
Create our configuration object
Now that we have created the interfaces, we can use Config.Net's ConfigurationBuilder to specify the format and location of our configuration and then build an object that we can use to access our configuration.
When using the ConfigurationBuilder class, we need to specify the interface type that matches the configuration file structure. In this case, our top-most interface is IAppSettings so we will specify that.
We then specify what configuration provider we want to use with the appropriate method. In this case since we want to use a JSON file called appsettings.json, we will use the .UseJsonFile("appsettings.json")
method (available in the Config.Net.Json package) and specify the JSON filename as a parameter. You might notice there is also a .UseJsonConfig()
method which looks similar, however, we are not going to use it since it doesn't seem to support writing to the configuration file, only reading from it.
We then build our final configuration object after configuring the builder.
using Config.Net;
using ConfigNetTutorial.Configuration;
namespace ConfigNetTutorial
{
class Program
{
static void Main(string[] args)
{
var settings = new ConfigurationBuilder<IAppSettings>()
.UseJsonFile("appsettings.json")
.Build();
}
}
}
Reading and writing configuration settings
We can now use our newly created object to read and write settings in the configuration file. Notice that we just have to use the properties we defined in our interface, Config.Net does the rest.
using System;
using Config.Net;
using ConfigNetTutorial.Configuration;
namespace ConfigNetTutorial
{
class Program
{
static void Main(string[] args)
{
var settings = new ConfigurationBuilder<IAppSettings>()
.UseJsonFile("appsettings.json")
.Build();
Console.WriteLine("Welcome to Config.Net Tutorial Application");
Console.WriteLine("===========================================");
Console.WriteLine($" - Version: {settings.Application.Version}");
Console.WriteLine($" - Beta Version: {(settings.Application.AllowBetaFunctionality ? "Yes" : "No")}");
Console.WriteLine(" - Support:");
Console.WriteLine($" - Name: {settings.Application.Support.Name}");
Console.WriteLine($" - Email: {settings.Application.Support.Email}");
Console.WriteLine($" - Phone: {settings.Application.Support.Phone}");
Console.WriteLine();
Console.WriteLine("Configure your theme");
Console.WriteLine("--------------------");
Console.Write("Primary Colour > ");
settings.Theme.Primary = Console.ReadLine();
Console.Write("Secondary Colour > ");
settings.Theme.Secondary = Console.ReadLine();
Console.WriteLine("Thank you!");
}
}
}
The program above prints the following in the console:
Welcome to Config.Net Tutorial Application
===========================================
- Version: 1.0.0
- Beta Version: No
- Support:
- Name: Ivan Kahl
- Email: [email protected]
- Phone: 030-555-3233
Configure your theme
--------------------
Primary Colour > #ac2121
Secondary Colour > #111111
Thank you!
And the appsettings.json file looks like this after running the program (notice how our theme colours were updated).
{
"Application": {
"AllowBetaFunctionality": false,
"Version": "1.0.0",
"Support": {
"Name": "Ivan Kahl",
"Email": "[email protected]",
"Phone": "030-555-3233"
}
},
"Theme": {
"Primary": "#ac2121",
"Secondary": "#111111"
}
}
Conclusion
I hope this article has given you a good overview of the Config.Net library and you have a better idea where you can use it in your projects. I have used it extensively in my projects and it works well. If you would like to learn more about Config.Net or contribute (both code-wise or financially), you can view the repository on GitHub here.
If you have any questions or suggestions, please leave them in the comments below.