I mentioned in my first post that we were using interfaces to represent our models and WHY we did it. So here’s the HOW of doing it.

Binding

As I mentioned, we used the model attribute to decorate our models when they are in the method signature. This attribute was based on the AbstractParameterBinderAttribute from MvcContrib (if you’re using ASP.NET MVC and NOT using MvcContrib, you’re probably re-inventing more than a few wheels) which is just a CustomModelBinderAttribute with a little bit of happy sprinkled in. Here’s what our binding looked like:

The GetViewData and SetViewData are pretty self-explanatory but the real heavy lifting is in that extension method. Let’s take a look at it.

DictionaryAdapter

We know that we have a giant dictionary holding on to our data and tedious mapping using strings make me itchy, not to mention it breaking my refactoring tool, so how do we push the values without them? DictionaryAdapter from Castle. This little known, under utilized piece of work was shown to me by Craig Neuwirt, it’s creator, and I’m constantly amazed at it’s usefulness. Observe the following extension method for ViewData:

It’s that simple. No, really. The DictionaryAdapter will match up the properties on the interface you defined with the corresponding elements in the ViewData and push their values into an instance of the model. All of that, without you even having to buy it dinner.

There’s more??

This approach worked great for us and gave us most of what we needed, however, this code doesn’t handle rehydrating objects from ActiveRecord – yet. But that’s a post for another night…

CORRECTION: Craig informed me that he did not create it originally but re-wrote it’s initial implementation to what it is now. Sorry for the misunderstanding.

My first podcast (the fifth for the series) is up – we discussed technical presentations and had a great time doing so. I’m very fortunate to work with such great people and had a wonderful time. Thanks to Allen and Mike for moderating and putting the whole thing together.

Brad Wilson tweeted asking about using interfaces for models in an ASP.NET MVC project and I was tempted to respond but figured this, rather than the 140 character limited avenue of Twitter, would be a better medium. The short answer is that we used binders and attributes to do our heavy lifting for us so that instead of our code looking like this:

Our model attribute was responsible for pulling in the values from our ViewData and then binding them using the DictionaryAdapter (probably one of the most powerful, under-documented pieces of the whole stack) from Castle.

Advantages

Doing this allowed us to keep our dealings with the models strongly typed (yes, this is NOT unique to using interfaces vs. classes), minimized the code needed for the model since it’s just an interface but also keeps anyone from “accidentally” pushing logic down into the model that belongs elsewhere.