Generic config section handlers

You can become a serverless blackbelt. Enrol in my course Learn you some Lambda best practice for great good! and learn best practices for performance, cost, security, resilience, observability and scalability. By the end of this course, you should be able to make informed decisions on which AWS service to use with Lambda and how to build highly scalable, resilient and cost efficient serverless applications.

It’s been a while since I had to create a config section handler and my god did I forget how cumbersome a process it is!

Instead of doing all these work to make a bespoke config section handler every time you want to parse some data out of the app.config file, wouldn’t it be nice to have a more generic, reusable component to do all the work for you? Well, turns out it wasn’t all that hard to make one either!

Broadly speaking, you usually want to parse either an object, or a collection of objects out of the config file, and they required slightly different handling so I ended up writing one for each.

Single Object

The single object case is fairly easy, all you need is an XmlSerializer for deserializing the XML node:

   1: public sealed class GenericConfigSectionHandler<T> : IConfigurationSectionHandler

   2: {

   3:     public object Create(object parent, object configContext, XmlNode section)

   4:     {

   5:         var xmlSerializer = new XmlSerializer(typeof(T));

   6:         var xmlNodeReader = new XmlNodeReader(section);

   7:         return xmlSerializer.Deserialize(xmlNodeReader);

   8:     }

   9: }

Assuming you have a simple class like this:

   1: [XmlRoot("MyClass")]

   2: public class MyClass

   3: {

   4:     public string Name { get; set; }

   5:

   6:     public int Age { get; set; }

   7: }

To parse it out of your app.config file, you need something like this in the config file:

   1: <configuration>

   2:   <configSections>

   3:     <section name="MyClass"

   4:              type="ConsoleApplication.GenericConfigSectionHandler`1[[ConsoleApplication.MyClass, ConsoleApplication]], ConsoleApplication"/>

   5:   </configSections>

   6:

   7:   <MyClass>

   8:     <Name>Yan</Name>

   9:     <Age>29</Age>

  10:   </MyClass>

  11: <configuration>

And your code will be the same as before:

   1: var myObj = (MyClass)ConfigurationManager.GetSection("MyClass");

Collections

Collections usually represent a whole new level of pain because to get an array of objects out of the config file you have to first create a wrapper object to hold the array. You then need to set up your config section to parse the wrapper object instead of the array itself, just an additional hoop you have to jump through to get something simple done…

Well, with this GenericCollectionConfigSectionHandler class hopefully you won’t ever have to do that again!

   1: public sealed class GenericCollectionConfigSectionHandler<T> : IConfigurationSectionHandler

   2: {

   3:     static GenericCollectionConfigSectionHandler()

   4:     {

   5:         // get the XmlRootAttribute element on the type

   6:         var type = typeof(T);

   7:         var xmlRootAttributes =

   8:             type.GetCustomAttributes(typeof(XmlRootAttribute), false)

   9:                 .OfType<XmlRootAttribute>();

  10:

  11:         // if an XmlRootAttribute is found then use its ElementName property as the

  12:         // root element name for the type T, otherwise, use the name of the type T

  13:         // as the default root element name

  14:         RootElementName =

  15:             !xmlRootAttributes.Any()

  16:                 ? type.Name

  17:                 : xmlRootAttributes.First().ElementName;

  18:     }

  19:

  20:     private static string RootElementName { get; set; }

  21:

  22:     public object Create(object parent, object configContext, XmlNode section)

  23:     {

  24:         var xmlSerializer = new XmlSerializer(typeof(T));

  25:         var xmlNodeReader = new XmlNodeReader(section);

  26:         var xdoc = XDocument.Load(xmlNodeReader);

  27:         var items =

  28:             xdoc.Descendants(RootElementName)

  29:                 .Select(e => (T)xmlSerializer.Deserialize(e.CreateReader()));

  30:         return items.ToArray();

  31:     }

  32: }

As you can see, this class is pretty simple, to use it your config file ought to look a little like this:

   1: <configuration>

   2:   <configSections>

   3:     <section name="MyClasses"

   4:              type="ConsoleApplication.GenericCollectionConfigSectionHandler`1[[ConsoleApplication.MyClass, ConsoleApplication]], ConsoleApplication"/>

   5:   </configSections>

   6:

   7:   <MyClasses>

   8:     <MyClass>

   9:       <Name>Yan</Name>

  10:       <Age>29</Age>

  11:     </MyClass>

  12:     <MyClass>

  13:       <Name>Yinan</Name>

  14:       <Age>29</Age>

  15:     </MyClass>

  16:   </MyClasses>

  17: </configuration>

So you see, no wrapper class required and you get an array of MyClass instances back:

   1: var myObjs = (MyClass[])ConfigurationManager.GetSection("MyClasses");

Liked this article? Support me on Patreon and get direct help from me via a private Slack channel or 1-2-1 mentoring.
Subscribe to my newsletter


Hi, I’m Yan. I’m an AWS Serverless Hero and the author of Production-Ready Serverless.

I specialise in rapidly transitioning teams to serverless and building production-ready services on AWS.

Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.

Hire me.


Check out my new podcast Real-World Serverless where I talk with engineers who are building amazing things with serverless technologies and discuss the real-world use cases and challenges they face. If you’re interested in what people are actually doing with serverless and what it’s really like to be working with serverless day-to-day, then this is the podcast for you.


Check out my new course, Learn you some Lambda best practice for great good! In this course, you will learn best practices for working with AWS Lambda in terms of performance, cost, security, scalability, resilience and observability. We will also cover latest features from re:Invent 2019 such as Provisioned Concurrency and Lambda Destinations. Enrol now and start learning!


Check out my video course, Complete Guide to AWS Step Functions. In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. There is something for everyone from beginners to more advanced users looking for design patterns and best practices. Enrol now and start learning!


Are you working with Serverless and looking for expert training to level-up your skills? Or are you looking for a solid foundation to start from? Look no further, register for my Production-Ready Serverless workshop to learn how to build production-grade Serverless applications!

Find a workshop near you