Generic config section handlers

You can become a serverless blackbelt. Enrol to my 4-week online workshop Production-Ready Serverless and gain hands-on experience building something from scratch using serverless technologies. At the end of the workshop, you should have a broader view of the challenges you will face as your serverless architecture matures and expands. You should also have a firm grasp on when serverless is a good fit for your system as well as common pitfalls you need to avoid. Sign up now and get 15% discount with the code yanprs15!

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; }


   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>


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


  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:     }


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


  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>


   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 I help companies go faster for less by adopting serverless technologies successfully.

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.

Skill up your serverless game with this hands-on workshop.

My 4-week Production-Ready Serverless online workshop is back!

This course takes you through building a production-ready serverless web application from testing, deployment, security, all the way through to observability. The motivation for this course is to give you hands-on experience building something with serverless technologies while giving you a broader view of the challenges you will face as the architecture matures and expands.

We will start at the basics and give you a firm introduction to Lambda and all the relevant concepts and service features (including the latest announcements in 2020). And then gradually ramping up and cover a wide array of topics such as API security, testing strategies, CI/CD, secret management, and operational best practices for monitoring and troubleshooting.

If you enrol now you can also get 15% OFF with the promo code “yanprs15”.

Enrol now and SAVE 15%.

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!