Complex configuration

So app settings can be useful. If you have a couple of properties and that you want to be configurable there are a number of options:

  • Database configuration
  • File / app / web configuration

A benefit of using a configuration file is that configuration transforms can be applied for different environments or builds. If you have a lot of configuration properties or want to store a more complex data structure this can be a pain to read into memory.

.NET gives you the ability to have a custom configuration section which can store information in XML format. This is great but takes a lot more work to get the data than an app setting key value pair. Step in Custom Configuration, its goal is to ease the pain. It automates the reading of the configuration and will load it into a typed C# class. Lets give an example:

<?xml version="1.0"?>
<configuration>

  <configSections>
    <section name="domainModelTemplate" type="CustomConfigurations.ConfigurationSectionLoader, CustomConfigurations"/>
  </configSections>

  <domainModelTemplate>
    <Configs>
      <ConfigurationGroup name="model">
        <ValueItems>
          <ValueItem key="CanExecute" value="true"/>
          <ValueItem key="Description" value="domain model template desciption field"/>
          <ValueItem key="NumberUnits" value="5"/>
          <ValueItem key="ModelType" value="TheirType"/>
        </ValueItems>
      </ConfigurationGroup>
    </Configs>
  </domainModelTemplate>

<startup><supportedRuntime version="v2.0.50727"/></startup>
</configuration>

A simple class can be used to load this information:

public class DomainModel
{
    public string Name { get; set; }

    public bool CanExecute { get; set; }
    public string Description { get; set; }
    public int NumberUnits { get; set; }
    public DomainModelType ModelType { get; set; }        
}

public enum DomainModelType
{
    MyType,
    TheirType,
    AnotherType,
}

We can create a configuration loader to isolate the use of custom configuration and simply return a strongly typed object to your business logic:

public static class ConfigurationLoader
{
    public static DomainModel LoadDomainModelTemplate()
    {
        return new Config("domainModelTemplate")
            .GetSection("model")
            .Create<DomainModel>();
    }
}

The main limitation of Custom Configuration is the XML it uses. It can become verbose if the model structures are pretty deep and complex. Currently it can not save the configuration back to the file, (but this is in on the issue list). The key features of the application are:

  • Strongly typed configuration
  • Complex data structures stored in XML
  • Not limited to the web / app configuration file
  • Can encrypt and decrypt custom configuration sections
  • Can have multiple configuration sections in one file

For more information and further examples please visit Custom Configuration.

Published: Friday, 01 May 2015