3

Reading Appsettings.json from Class Library projects in .NET

 8 months ago
source link: https://jamiemaguire.net/index.php/2023/12/23/reading-appsettings-json-from-class-library-projects-in-net/?utm_campaign=reading-appsettings-json-from-class-library-projects-in-net
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

C#

Reading Appsettings.json from Class Library projects in .NET

Pasted-6-816x446.png

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.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK