Software Architect / Microsoft MVP (AI) and Technical Author

C#

Reading Appsettings.json from Class Library projects in .NET

I like to encapsulate as many business rules and logic as possible in class libraries.

 

These are often used in web APIs, Azure Functions or wherever is required.

 

Sometimes you want to access values from an appsettings.json file that exists in a class library project but not pass values or JSON references through different layers of your solution to said class library.

 

This short post shows you how to do this.

 

Note: This is more for my own reference and when creating prototypes locally, but you may find it useful.

A better approach for cloud solution configuration management is to use Azure Key Vault or Azure App Configuration.

~

Appsettings.json

We have the following values in the JSON file:

{
 "YourKey1": "YourValue1",
 "YourKey2": "YourValue2"
}

 

Creating a Helper Class

A static helper class ApplicationConfiguration is created.

It imports the namespace Microsoft.Extensions.Configuration.

The appsettings.json file is loaded from the directly the assembly is running in.

You can see this here:

using Microsoft.Extensions.Configuration;

namespace YourClassLibrary.API.Utils
{
    public static class ApplicationConfiguration
    {
        private static IConfigurationRoot _configuration;

        static ApplicationConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            _configuration = builder.Build();
        }

        public static string GetSetting(string key)
        {
            return _configuration[key];
        }
    }
}

 

A public method GetSetting is created.  This key parameter lets you specify a key in your existing appsettings.json file to fetch the value you need.

~

Using the Method

You can see this in action here:

var yourvalue1 = ApplicationConfiguration.GetSetting("YourKey1");
var yourvalue2= ApplicationConfiguration.GetSetting("YourKey2");

~

Summary

That’s it. Short and sweet!

JOIN MY EXCLUSIVE EMAIL LIST
Get the latest content and code from the blog posts!
I respect your privacy. No spam. Ever.

1 Comment

  1. Angel

    Thanks for that answer, I was stuck for about 2 days trying to understand why my _configuration it was always null, with that ApplicationConfiguration solved all my problems, thanks a lot.

Leave a Reply