appsettings.net-standard-2.0system.configuration

Is it possible to use .Net Standard System.Configuration.ConfigurationManager.AppSettings with an appSettings.json file


I would like to be able to build .Net Standard libraries that can retrieve their own configuration information whether they are called from a Net Framework or a Net Core application.

System.Configuration.ConfigurationManager has been added to Net Standard. I have proven that I can use this to pull from a traditional app or web.config file such as this:

var value = ConfigurationManager.AppSettings["testString"];

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="testString" value="xxwx"/>
    <add key="testInt" value="234"/>
    <add key="testBool" value="true"/>
  </appSettings>
<startup>
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
</startup>
</configuration>

I would like to be able to pull the same value using the same code from an appettings.json file. Something like the following:

{
  "appSettings": [
    {
      "Key": "testString",
      "Value": "xxwx"
    },
    {
      "Key": "testInt",
      "Value": "234"
    },
    {
      "Key": "testBool",
      "Value": "true"
    }
  ]
}  

Can someone tell me if this is possible using System.Configuration from Net Standard 2.0 to read an appSettings.json file? The real purpose here is that I do not want to have consuming applications have a need to understand configuration parameters of libraries. I also want to be able to use the same libraries from Net Framework and Net Core applications. Alternatively, is there a better way to achieve this?


Solution

  • To the best of my knowledge, that functionality is provided by Microsoft.Extensions.Configuration, which is compatible with .NETStandard 2.0.

    You can see an example of loading the configuration here:

    var builder = new ConfigurationBuilder()
         .SetBasePath(Directory.GetCurrentDirectory())
         .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
         .AddJsonFile($"appsettings.{EnvironmentName}.json", optional: true, reloadOnChange: true)
         .AddEnvironmentVariables();
    Configuration = builder.Build();
    

    This will load an appsettings.json file as well as an environment specific app settings file (ex: appsettings.Production.json).

    To get the settings, you can see more about it in the Microsoft Docs.