Skip to content

ConfigurationManager

Michael Brown edited this page Apr 18, 2020 · 8 revisions

The built-in ConfigurationManager supports all existing features of Microsoft's ConfigurationManager with some additional extensions and loading support. Both JSON and XML are supported, and additional features that allow for grouped settings and type binding.

Usage Examples

You can use standard AppSettings and bind them to a specific type:

var isEnabled = ConfigurationManager.AppSettings["IsEnabled"].As<bool>();

or using the alternate Get syntax:

var isEnabled = ConfigurationManager.Get<bool>("IsEnabled");

Traditional Custom Sections

Traditional custom sections can be bound to a type as well, such as NLog's typical configuration. Keep in mind this particular example only works in .Net Framework but this is just an NLog limitation.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
  </configSections>
  <nlog>
    <targets async="true">
      <target type="Trace" name="trace" layout="${longdate}|${level:uppercase=true}|${itn-activity-id}|${logger}|${message}|${exception:format=tostring}" />
    </targets>
    <rules>
      <logger name="*" minLevel="Trace" appendTo="trace" />
    </rules>
  </nlog>
</configuration>
var nlogConfig = ConfigurationManager.GetSection("nlog").As<NLog.Config.XmlLoggingConfiguration>();

AnyConfig Custom Sections

AnyConfig also supports custom sections that don't require configSections registration or custom section handlers. They are a much simpler way to do custom sections.

Caveat: It is worth noting however, that certain Microsoft libraries (such as XmlSerializer) have a core dependency on System.Configuration and will cease to function because they consider the Xml to be invalid. Why they chose to read configurations for these libraries is beyond me, but it's what we are stuck with. Because of such issues is why AnyConfig implements its own data serializers.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <MyTestConfiguration>
    <IsEnabled>true</IsEnabled>
    <Name>My name</Name>
    <Url>http://localhost</Url>
    <CustomEnum>EnumValue</CustomEnum>
    <Server>
      <Port>1234</Port>
      <IP>127.0.0.1</IP>
    </Server>
  </MyTestConfiguration>
</configuration>
var myTestConfiguration = ConfigurationManager.GetSection("MyTestConfiguration").As<MyTestConfiguration>();

Encrypted sections

ConfigurationManager supports legacy encrypted sections for both DPAPI and Rsa providers:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
    <EncryptedData>
      <CipherData>
        <CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAApb+sVGe2VE+lMjIbVJEHSQQAAAACAAAAAAAQZgAAAAEAACAAAAAdFj8JnfBYcQgOXgykl0GMMr+LNbLvuHcKkORXyZMYYQAAAAAOgAAAAAIAACAAAABTTjVYGFlNx6Nrszzxx0zPVpv8pd7vvJTUZKkcoJ+qPOAAAABowVl8KfiD4E71oT4U/uhDFqgyp4ZSDkm8mBBIQzmCES7C62UgHhxlptfV37x4QSv2DvOdloBylQbeVYuRckLTgSondMNLZ+1O7QROxfg9NxwD0Kv7h68NGWgM06r85UbHK1PTuidAV+9JDD64zecyjaiDXcf+IWXr5RxcgHZZkhqNNdYn0PQU31EOvlwePZY/NIrWywF6a6mivHDLMjgdLRY6Xb8vpQyQCPrZP+lJjN4g9uULlM/pq4qw2exQ7KZmYE9+n4NByf+7ZbxLm+qUk7HuyM2wRHehrlnR/+1teUAAAAAwNlddSP6JBjfjkSkGtIwYfqSCIz6XEO/KQLikv9N4HNUiTWQdlwi8x/KhxuLvUvjoS4vYBQ+S9+APTvW5P+Bn</CipherValue>
      </CipherData>
    </EncryptedData>
  </connectionStrings>
</configuration>
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStrings = config.GetSection("connectionStrings");
Assert.IsTrue(connectionStrings.SectionInformation.IsProtected);
Assert.AreEqual("host=localhost;", ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString);

You can also use the alternate Get syntax:

var config = ConfigurationManager.Get<SectionCollection<ConnectionStringPair>>("connectionStrings");
var connectionString = config["TestConnection"].ConnectionStringSetting.ConnectionString;

AnyConfig grouped appSettings

If you use the alternate anyConfig section instead of appSettings you can group your settings:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings></appSettings>
  <anyConfig>
    <add key="rootName" value="rootValue1" />
    <settings>
      <add key="name" value="value1" />
      <add key="isEnabled" value="true" />
    </settings>
    <config>
      <add key="name" value="othervalue1" />
      <add key="isEnabled" value="false" />
    </config>
  </anyConfig>
</configuration>
var settingsName = ConfigurationManager.AnySettings["settings"]["name"]; // value1
var configName = ConfigurationManager.AnySettings["settings"]["name"]; // othervalue1
var rootValue = ConfigurationManager.AnySettings["rootName"]; // rootValue1

You can also use the alternate Get syntax:

var settingsIsEnabled = ConfigurationManager.Get<bool>("settings", "isEnabled"); // true

JSON Support

You can use ConfigurationManager with an appsettings.json (or any json file) should you need.

{
  "AppSettings": {
    "BoolSetting": true,
    "StringSetting": "TestValue",
    "IntSetting": 1,
    "CustomEnumSetting": "Second",
    "CustomEnumNumericSetting": 2,
    "TestConfigurationObject": {
      "Name": "TestName",
      "Value": "TestValue"
    }
  },
  "ConnectionStrings": [
    {
      "name": "TestConnection",
      "connectionString": "host=localhost;"
    }
  ]
}

If you wish to use ConfigurationManager in a .Net Core project, your appsettings.json will be automatically detected. However on .Net Framework you will need to specify that you wish to load a JSON file as your assembly will have a basic configuration attached so it needs to be told what to do.

ConfigurationManager.ConfigurationFilename = "appsettings.json";
var connectionString = ConfigurationManager.ConnectionStrings["TestConnection"];
var stringSetting = ConfigurationManager.AppSettings["StringSetting"];

You can also use it to bind custom sections:

{
  "TestConfiguration": {
    "BoolSetting": true,
    "StringSetting": "TestValue",
    "IntSetting": 1,
    "CustomEnumSetting": "Second",
    "CustomEnumNumericSetting": 2,
    "TestConfigurationObject": {
      "Name": "TestName",
      "Value": "TestValue"
    }
  }
}
ConfigurationManager.ConfigurationFilename = "appsettings.json";
var testConfiguration = ConfigurationManager.GetSection("TestConfiguration").As<TestConfiguration>();

Clone this wiki locally