Taming dictionaries to strongly-typed interfaces with Castle DictionaryAdapter

So Castle is one of those projects that seems to sit behind a lot of technologies (Moq, NHibernate) but which maybe people don’t look at directly. Which is a shame, because it’s pretty special. Here’s one block of code with a really interesting effect;

// Let's define an interface...

public interface ICustomerProfile
{
    string UserName { get; set; }
    int NumberOfTimesSiteAccessed { get; set; }
}

// now let's have Castle give us a 
// strongly-typed wrapper onto a 
// simple dictionary object;
class Program
{
    static void Main(string[] args)
    {
        var dictionary = new Dictionary<string, object>();
        var factory = new Castle.Components.DictionaryAdapter
            .DictionaryAdapterFactory(); 
        ICustomerProfile proxy = factory.GetAdapter<ICustomerProfile>(dictionary);
        proxy.UserName = "John Appleseed";
        Console.WriteLine(proxy.UserName);
        Console.WriteLine(proxy.NumberOfTimesSiteAccessed);
    }
}

This uses Castle’s DictionaryAdapter to create a strongly-typed interface to a dictionary. Castle is implementing ICustomerProfile for us, and intercepting any calls, translating them into calls to a dictionary. Those two lines in red do all the interesting work.

What we’ve done is taken something that feels dynamically typed and ‘frameworky’ (the dictionary) and make it a proper, strongly-typed domain object again.

As the docs point out, this is really useful when dealing with ASP.NET, where there are all kinds of dictionaries, like ViewState, Session state, and HttpRequest.Form contents flying about.

You could do this by writing your own adapter class, get and set accessors for each property, but why bother?

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 )

Facebook photo

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

Connecting to %s