11

Taming dictionaries to strongly-typed interfaces with Castle DictionaryAdapter

 3 years ago
source link: https://stevedrivendevelopment.com/2013/09/28/taming-dictionaries-to-strongly-typed-interfaces-with-castle-dictionaryadapter/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK