AutoMapper Formatters are Cool - ASP.NET MVC Style

I have a new respect for AutoMapper after reading Matt Hinze's post showing off AutoMapper in Nerddinner. I briefly touched upon AutoMapper via Custom ActionFilters at the last Tampa ASP.NET MVC Group Meeting. Although the focus of my brief presentation was on custom ActionFilters and not AutoMapper, I realize more and more that my example really didn't do AutoMapper justice.

After reading Matt's post I really wanted to experience the AutoMapper Formatters for myself. I liked the idea of removing much of the repetitive formatting from the view and applying it in AutoMapper.

Given a Post Domain Model Entity and a PostList View Model Class ( not important enough to show ), I can create a simple mapping complete with a couple of Custom Formatters as such:

 

Mapper.AddFormatter<HtmlEncodeFormatter>();

Mapper.CreateMap<Post, PostList>()

    .ForMember(p => p.TotalComments, o => o.MapFrom(p => p.Comments.Count()))

    .ForMember(p => p.BlogTitle, o => o.AddFormatter<TitleFormatter>());

 

Really quick and dirty I created a couple of formatters just to test out the functionality:

 

public class TitleFormatter : BaseFormatter<string>

{

    protected override string FormatValue(string value)

    {

        return string.Format("-{0}-", value);

    }

}

 

public class HtmlEncodeFormatter : IValueFormatter

{

    public string FormatValue(ResolutionContext context)

    {

        return HttpContext.Current.Server.HtmlEncode(context.SourceValue.ToString());

    }

}

 

The HtmlEncodeFormatter is applied globally ( you can set-up profiles, etc. ) and hence everything is encoded properly without the need for Html.Encode placed everywhere in the Views. The TitleFormatter is just applied on the BlogTitle Property and just wraps the title between two dashes for kicks and nonsense :)

Either via the AutoMap Attribute or as such:

 

BlogRepository repository = new BlogRepository();

Blog blog = repository.FetchById(1);

 

var postList = Mapper.Map(

    blog.Posts,

    typeof (IEnumerable<Post>),

    typeof (IEnumerable<PostList>));

 

We can get our IEnumerable<PostList> converted from IEnumerable<Post>.

I still have this overall question as to the order of how formatters are executed, etc., but I was quite excited when I saw the formatters being applied to the properties appropriately.

Cool stuff for a Friday! Makes me want to dig into AutoMapper even more!

 

David Hayden

 

posted on Friday, July 17, 2009 12:53 PM

Main

David Hayden Google +

David Hayden Twitter

Health & Fitness

JavaScript Patterns Book Review

HTML 5 and CSS3 - Develop with Tomorrow's Standards Today

Professional ASP.NET Design Patterns Book Review

Beginning Mac Programming Book Review

C# in Depth Book Review

ASP.NET MVC

Orchard CMS

Categories