Coding with Titans

so breaking things happens constantly, but never on purpose

HowTo: Split web.config file

Among all the features of ASP.NET framework, there is one I love the most:

moving parts of the configuration (i.e. Web.config) into separate files!

It’s just it, a little something, that makes life so much easier by:

  • less effort while working with GiT (conflicts are subtle and with better context, changing braches mostly let you move also your local changes, or reset parts of it)
  • quicker navigation, as they are files with my custom naming convention (via R# hit Ctrl+T and start typing the name using only first uppercase letters of the file to open it)
  • custom sections can also be put in an another file.

In my typical scenario, I move away sections responsible for:

  • database connection strings (as they change the most)
  • WCF service definitions (behaviors, bindings and services themselves) as they can occupy lots of space
  • and definition of my custom section of continuously evolving list of options (titanSection).

Sample web.config

As the picture above shows separation is achieved simply by using “configSource” attribute inside a section that is supposed to be outsourced. And that’s all – just name the file, create it and inside that file define directly the same section tag as from Web.config. But this time put there a real content.

For example the content of database connection-strings (named by me: Web.Connections.config, that is located next to Web.config), could look like that:

Separate file with database connection-strings

You can name the files whatever you like. However I highly encourage you to have a naming schema. Anything that starts with ‘Web’ and has an extension ‘.config’ would be probably sufficient and also be easy enough to remember, what is inside.

Final though on custom section. It might be placed in separate location in identical way. Only difference is that his kind of section should have a code-behind C# class inheriting from ConfigurationSection with all public properties marked with ConfigurationPropertyAttribute attribute (and inner tags define as separate classes inheriting from ConfigurationElement).

Once the class is completed, inside Web.config there should be a link defined between that class and a custom name of the section. Notice the “configSections” and a “section” entry on the picture above. It contains the name of the “titanSection” section and also points to a TitanConfigSection class (with an assembly name) that will handle accumulation of all settings.

Then only the imagination stops you from creating config complicated as the one below:

Titan Config

I hope it proved useful for you too!