Skip to content
edpollitt edited this page Sep 25, 2019 · 31 revisions

AutoConfig is an automagical, convention-based, customisable, extensible library for mapping configuration files to POCO C# objects/interfaces with the absolute minimum of code.

AutoConfig will handle nearly all requirements by convention out of the box, mapping simple types, strings, enums, nullables, enumerables, collections, lists, arrays, dictionaries, and arbitrarily complex nested types.

Additionally, AutoConfig is fully customisable without the use of Attributes, ensuring your configuration POCOs remain completely uncoupled from the mapping library.

Installation

via NuGet

Install-Package Nerdle.AutoConfig

Simple usage

Define an interface or class for your configuration settings.

public interface IExampleConfiguration
{
    string Foo { get; }
    DateTime Bar { get; }
    DayOfWeek Baz { get; }
}

Add a custom configuration section in app.config / web.config. By default, section names and element names will be inferred from the requested type by convention.

<configuration>
  <configSections>
    <section name="exampleConfiguration" type="Nerdle.AutoConfig.Section, Nerdle.AutoConfig" />
  </configSections>
  <exampleConfiguration>
    <foo>hello</foo>
    <bar>21 July 1969</bar>
    <baz>Monday</baz>
  </exampleConfiguration>
</configuration>

AutoConfig can map your configuration to either a concrete class or an interface. When requesting an interface mapping, an interface implementation will be dynamically generated by the library at runtime. (Note that it is therefore more efficient to map to a concrete type if you already have an appropriate implementation defined.)

[Test]
public void MappingTheExampleConfiguration()
{
    var result = AutoConfig.Map<IExampleConfiguration>();

    result.Should().BeAssignableTo<IExampleConfiguration>();

    result.Foo.Should().Be("hello");
    result.Bar.Should().Be(new DateTime(1969, 7, 21));
    result.Baz.Should().Be(DayOfWeek.Monday);
}

Mapping from attributes

AutoConfig can map from attributes (for simple types and strings), elements, or a mixture of both.

 <exampleConfiguration foo="hello" bar="21 July 1969" baz="Monday" />

Clone this wiki locally