Monday, July 12, 2010

Keeping Web.Config nice and tidy

I've been digging through .Net blogs to get some ideas about how to tidy up the web.config file.

OdeToCode recommends building an encapsulation layer between Web.Config and your code, so that the string values keys used to access Web.Config settings are replaced with property names of a Configuration class.   This also provides a place for casting not string values, and for replacing the source of the data at a later point in a way that will be transparent to the rest of the application.


The post also explains two ways to break out Web.Config into separate files.  First, the appSetting element has an optional "file" attribute, that provides keyword level overrides in a separate file.  This allows you to put environment specific values in separate files, while your Web.Config contains only universal settings or default values.

The beauty of this approach is that Web.Config can now be included in source control and deployed as part of the project, while each environment (Development, Test, Production) will have an override file that is not part of source control or the project, so will not be overwritten during deployment.  The override file will contain values such as email addresses that change between development, testing, and production.

In addition to the "file" attribute of the appSettings element, as of .Net 2.0 each configuration section (e.g. connectionStrings, etc.) can have a configSource element.  However, as the MSDN documentation explains, "you must move the entire section to the separate file because there is no merging of element settings."  So for granular replacement of appSettings, use "file", but for a wholesale breaking out of a section to another file, use configSource.

Finally, Sitecore users have the "sc.include" element.  There's a whole Sitecore.Configuration API, which I'll explore in a later post.

By the way, Web.Config goes on a diet with .Net 4.0.  A Microsoft guy explains that the 126 lines of  Web.Config boilerplate is due to making .Net 3.5 do different things from .Net 2.0 with the same runtime.  .Net 4.0 has a new runtime, so the config files are very small.

No comments:

Post a Comment