Making the tedious exciting – Automapper

If you take it as a given truth, that you do not want your presentation layers to be exposed to Domain Objects directly, then you need some way of “mapping” them to a Presentation Model/DTO structure. Developers hate writing this code. It is boring, fragile and laborious to test.

There is a better way! There is a mature project called AutoMapper, developed by Jimmy Bogard.
I watched a short episode of DotNetRocks TV which had me sold.

AutoMapper generally works via convention. In the simplest case, the names of your properties/methods need to match on the source and destination object. So, if you have a “Name” property on your Domain Object and on your Presentation Model, this will be mapped automatically. All you need to do is configure the types that can be mapped together during application initialisation.

Where this convention over configuration is not sufficient, AutoMapper also supports Custom Formatting, Conversion and Resolving, so you can flexibily flatten or project your domain types onto other objects. It seems to be very flexible and it was easy to create the Presentation Model I wanted. The project seems mature enough to cover just about any use case you could have.

A really nice feature is the Configuration Validation checking, which will point out errors or omissions resulting in the mapping from one object to the other, which you can call from a unit test:

[Test]
public void TestMappingsAreGood()
{
     Program.AutoMapperConfiguration();
     Mapper.AssertConfigurationIsValid();
}

I have created a small Visual Studio Solution which contains the early results of my AutoMapper experimentation that I hope will illustrate the frameworks power and ease of use.AutoMapper Example Project.

For further samples, the source includes a Samples Project

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
This entry was posted in Uncategorized. Bookmark the permalink.