Custom Sitecore Configuration: Part 1, Introduction

I’ve spent quite a bit of time looking into the way that Sitecore configuration can be used.  It has some fairly novel features in it, and while it’s becoming less relevant as support for dependency injection in Sitecore matures, I don’t think it’s going anywhere.  All the same, it’s quite useful for adding flexibility to your Sitecore customisations, or for piggybacking on to provide custom configuration for your own modules and sites.

You can use the Sitecore configuration in three main ways:

  • Use Settings.GetSetting(string) to retrieve a string value
  • Use Factory.GetConfigNode(string) to retrieve an XmlNode matching the given XPath.
  • Use Factory.CreateObject(string, bool) (or its various overloads) to make Sitecore create an instance of a particular type.

With the latter, you can go further and do handy things such as sending constructor parameters, invoking methods, populating properties and even creating further objects.

I intend to do a few posts on this subject, covering:

  1. Introduction and using Sitecore configuration to control settings or an XML document (this post);
  2. Basics of using Sitecore configuration to create and populate objects;
  3. Some more advanced tricks you can use, like refs and hints.

So, the first question is usually: why should I use the Sitecore configuration instead of appSettings or a custom configuration section?  The answer varies from project to project; but typically the following points tip the scales towards using Sitecore configuration:

  1. Very little coding is needed to use it
  2. The functionality available out-of-the-box is comprehensive
  3. You can use configuration include files to patch your configuration
  4. You can easily see the state of your configuration using showconfig.aspx or Sitecore Rocks

Being able to use include files is particularly useful if you’re trying to create a module, and it also fits in with what should be your general approach to configuration in any Sitecore solution.

Creating custom settings is the simplest of all uses for the Sitecore configuration; it’s an easy replacement for appSettings and usually all that is needed for most projects.  I would suggest prefixing your custom setting names with your project name (or similar) to prevent any clashes with settings Sitecore might add in the future or other modules you might install.  Adding your settings is easy, just add a configuration include file like the following to your website:

<?xml version="1.0"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/"
               xmlns:set="http://www.sitecore.net/xmlconfig/set/">
    <sitecore>
        <settings>
            <setting name="MySetting" value="MyValue" />
            <setting name="LifeUniverseAndEverything" value="42" />
        </settings>
    </sitecore>
</configuration>

You can then create a class to neatly access your new settings.  You can read the settings once and stick the values into properties, or you can call the GetSetting methods on-demand.  Many people go for the former, and keep that object (or group of objects) around for the lifetime of the application. The setting values are cached by the Sitecore API regardless, so it doesn’t make a massive amount of difference which option you choose (unless you plan to fiddle with your settings at run-time).  Depending on which approach you go with, you’ll end up with something like the following:

public class Settings
{
    public int MeaningOfLife
    {
        get { return Settings.GetIntSetting("LifeUniverseAndEverything", 0); }
    }

    public string MySetting
    {
        get { return Settings.GetSetting("MySetting"); }
    }
}

You might notice that I’ve used a method called GetIntSetting: there are a few helper methods to give you access to the typical set of commonly-used types (int, bool, double, long), most of these require a default value as a second parameter, which will be returned if the setting is not found (also an option for strings).  Anything other than that you’ll have to read as a string and parse yourself.

So, as I mentioned earlier, custom settings are good for replacing appSettings, but are only really suitable for simple lists of key-value pairs.  Sitecore also supports getting a configuration XML node directly from the HTML and creation of whole object maps through configuration.  I plan to cover the latter in the next post, as it has some useful capabilities.  In comparison, accessing the configuration XML is a little pointless; however I’ll included it for completeness.

Sitecore treats its configuration as an XML document: it loads it, it applies some patches to it, replaces some stuff; but it’s still an XML document underneath it all.  Therefore, there is no reason that you cannot add your own elements into the XML where you like.  I’d make the same point as I did with the setting names, which is that whatever name you choose, you should try and pick something that isn’t likely to suddenly appear in the Sitecore configuration from another source.  Let’s say you put the following configuration include file into your solution:

<configuration xmlns:p="http://www.sitecore.net/xmlconfig/"
               xmlns:set="http://www.sitecore.net/xmlconfig/set/">
  <sitecore>
    <myCustomFragment>
        <!-- insert random XML here -->
    </myCustomFragment>
  </sitecore>
</configuration>

Making the following simple call will get you the matching XML fragment from the patched configuration XML:

Factory.GetConfigNode("myCustomFragment")

The string provided is an XPath statement that should match a single node, and is relative to the root element of the configuration section (so <sitecore>, not <configuration>).  It’s also worth noting that due to its relative age, everything uses XmlDocument and its associates rather than XDocument.  Useful for small tasks, but for the majority of things it’s faster and easier to just let Sitecore create the objects for you.

That’s it for now, I’m aiming to have the next instalment up later this week; I’ll add links to the post when it’s up.