Home > Programming > Strongly typed dictionaries

Strongly typed dictionaries

I recently stumbled across the DictionaryAdapter component, which is part of the Castle Project. Some of the issues with storing settings in a centralized configuration file is that you’ll typically need to access these values using magic strings and receive back untyped data.

  <add key="MyFile" value="C:\temp\file.txt" />
  <add key="NumberOfItems" value="23" />
  <add key="SomeReallyLongAndUglyItemName" value="hello world" />

The DictionaryAdapter solves these issues by creating a strongly typed wrapper around these key/value stores or dictionaries. We simply create an interface that matches what we expect to receive back:

public interface IApplicationConfiguration
    string MyFile { get; set; }
    int NumberOfItems { get; set; }

    string HelloText { get; set; }

NumberOfItems is now strongly typed and the property HelloText maps to the key SomeReallyLongAndUglyItemName.

DictionaryAdapterFactory factory = new DictionaryAdapterFactory();
var config = factory.GetAdapter<IApplicationConfiguration>(ConfigurationManager.AppSettings);


The default convention matches the name of the property of the interface to the key in the dictionary. There are various attributes that are available that allows you to map different keys to different properties.  For example, the Key attribute above allows you to map a property to an unrelated key in the dictionary. More information on attributes can be found on the Castle Project wiki.

Using the DictionaryAdapter to create strongly typed wrappers for configuration allows my tests that are dependent on these dictionaries to be more flexible.

var stub = MockRepository.GenerateStub<IApplicationConfiguration>();
stub.Stub(x => x.HelloText).Return("woot");

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: