Storing C# app settings with JSON

JSON format has been a standard used amongst many different framework and languages for quite a few years now. It’s so cool, that even the .NET Core team have decided to include it in its framework which results in e.g. being able to store the application settings within a JSON file, which is much more human readable and less bloated than the old one App or Web.config written using the XML.
In today’s post, I’d like to present how easy it is to create your own JSON configuration reader and move the application settings to such file.


 

To begin with, let’s define our goal – we want to have a single config.json file in order to store the separate settings within the sections in this file. And of course, we want this file to be automatically mapped to the corresponding C# classes and later on injected using some IoC framework. We will create a very simple and naive console application, that tries to connect to the database and create a new user account using the provided email and password.
This would be our configuration:

And the classes:

Before we dive into the actual implementation of the ISettingsReader, let me just paste the code that will try to mimic some business logic. Let’s start with the user entity:

Next, focus on the database provider:

And finally, the application service:

Ok, that was the necessary code just to make this example something a little bit more than just a single interface and its implementation. So, here comes the part that you’ve been waiting for, just make sure that you install the Newtonsoft.Json NuGet package first:

Really, not too much code as for the simple class that can read the configuration file, ain’t it? And if you don’t want to use the protected accessor, you can skip the ContractResolver part.

We’re almost finished. Let’s plug all of that stuff into some IoC library – I’ll use the Autofac, yet feel free to chose whatever you like.

And eventually, the actual Program.cs source code:

Run the application now and you will see all of the settings correctly injected into the services. You can use this solution with any other application type as well (Web, WPF etc.).

Settings Reader App

Settings Reader App

The only important thing here is to set the config.json file to have a Build Action of type Content and either Copy Always or Copy if newer setting, so that it’s available for the application (or just keep it somewhere else and fix the configuration file path).

Also, if you don’t want to use the sections, you can choose the Load() instead of LoadSection() and have all of the properties stored within a root of the configuration file.

And that’s all – you can download this example here.

25 Comments Storing C# app settings with JSON

  1. Pingback: Storing C# app settings with JSON - How to Code .NET

  2. Pingback: typeof(arunselvakumar); | //Build June 7, 2016

  3. Pingback: The week in .NET – 06/07/2016 | .NET Blog

  4. Pingback: The week in .NET – 06/07/2016 | Tech News

  5. Andrew Lock

    It’s worth noting that most of this you get for free if you use the IOptions pattern – injecting your ‘DatabaseSettings’ class into a service becomes a one liner in ConfigureServices:

    services.Configure(Configuration.GetSection(“Database”));

    Your database constructor then becomes:

    public Database(IOptions databaseSettings)
    {
    _databaseSettings = databaseSettings.Value;
    }

    I have a post about it here: https://andrewlock.net/how-to-use-the-ioptions-pattern-for-configuration-in-asp-net-core-rc2/

    Reply
      1. Andrew Lock

        Oops, yes you’re right, I meant to mention that.

        Just to be clear, it’s a feature of ASP.NET Core – I believe it requires netstandard1.1, so it can be used in both .NET Core and .NET Framework/mono 4.5+

        Nie post:)

        Reply
        1. Piotr Gankiewicz

          Exactly and that’s why I wrote thist post so that devs who are not using .NET Core yet, could implement such feature on their own if they need it :).
          Thanks!

          Reply
  6. Dat AU DUONG

    Piotr/Andrew,

    Thank you for sharing the idea of storing configuration in json, it is very useful.

    I have a problem where the User Id and Password store at the configuration file are in plain text.

    Do you know how I can overcome this problem?

    I want to create c# winform application where I need to connect to database, but at the same time, this need to be deployed to other user. I don’t want the userid and password to be exposed and also I want this to be updatable on the client side.

    Likely to change:
    Database Server Name, Database Name, User Id and Password.

    Thanks in Advance.
    Regards Dat.

    Reply
    1. Piotr Gankiewicz

      Hi Dat,
      I’m glad that you find this solution to be useful. Speaking of storing credentials, what you can do about it, is to keep them encrypted in the settings file, however, you have to bear in mind that you need to store somewhere an encryption key (e.g. in system’s registry) in order to be able to decrypt the settings.
      In order to achieve such goal, you need to create your own ContractResolver and IValueProvider that you can pass to the Newtonsoft.Json settings.
      Please take a look at the following sample that I’ve taken from one of my projects – it’s not a 100% solution, as you still need to decrypt the data within this code, but it shouldn’t be too difficult and hopefully will give you the initial idea how to overcome your issue.

      https://gist.github.com/spetz/e1567775608e9dbd041137e59cd3be25

      If you have any further question, please let me know!

      Cheers

      Reply
    1. msp

      excuse me. i removed the word “IoC” and changed first “Container” to “Container_”

      Reply
  7. thecury

    Thanks very much indeed for this insight. I used it in a webapi 2 project and even though settings objects just resolved all the same, the property values turn out to be null

    Reply
      1. Diego

        it turns out the problem was with the path. The file json was not being found at runtime and that’s why the properties were null.

        Reply
  8. Chris

    Thanks for your example but “storing settings” includes for me the possibility to save settings, which is missing in your example. You can only read with your methods. If you’ve got time you could add the saving part to complete this example.

    Reply
  9. Tahir

    Piotr this is great I was looking to move some windows registry settings out of a few classes into a JSON file and I had similar ideas.

    Thank you for the heads up!

    Reply

Leave A Comment

Your email address will not be published. Required fields are marked *