Reading Appsettings.json from Class Library projects in .NET
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.
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:
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:
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:
Summary
That’s it. Short and sweet!
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK