Skip to content

ConfigurationManager

Michael Brown edited this page Apr 4, 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>();

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>();

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

// <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>
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

Clone this wiki locally