Thursday, May 31, 2012

One library every MVC project should not be without


One tool that I’ve found particularly useful in an MVC project is AutoMapper.

“A convention-based object-object mapper. 100% organic and gluten-free. Takes out all of the fuss of mapping one object to another.” AutoMapper

In my experience, in almost every get action method, a view model representation of the domain object needs to be constructed to be displayed in the view. With AutoMapper this is done automatically for you.


Without AutoMapper:

public ActionResult ManualMapping()
{
    var company = CompanyBuilder.Get();
    var companyViewModel = new CompanyViewModel
                               {
                                   Name = company.Name
                               };

    var persons = new List<PersonViewModel>();
    foreach (var person in company.Persons)
    {
        var personViewModel = new PersonViewModel
                                  {
                                      FirstName = person.FirstName,
                                      LastName = person.LastName,
                                      StartDate = person.StartDate != null
                                                  ? person.StartDate.Value.ToString()
                                                  : "",
                                      EndDate = person.EndDate != null
                                                ? person.EndDate.Value.ToString()
                                                : ""
                                  };
        persons.Add(personViewModel);
    }

    companyViewModel.Persons = persons;

    return View("Companies", companyViewModel);
}

With AutoMapper:

public ActionResult AutoMapping()
{
    return View("Companies", Mapper.Map<Company, CompanyViewModel>(CompanyBuilder.Get()));
}

Configuration:

public class CompanyInitialiser
{
    public void Initialise()
    {
        Mapper.CreateMap<Company, CompanyViewModel>();
        Mapper.CreateMap<Person, PersonViewModel>();
    }
}

With AutoMapper our action method in the 2nd code snippet looks so much simpler and neater!

Benefits:
  • Thin controller methods
  • Configuration fully unit testable
  • Reusable mappings (don't need to populate view models every time where needed)
  • Null substitution
  • Mapping inheritance
These are but a few added benefits when using AutoMapper and this is just a simple mapping scenario.
AutoMapper is very robust with the most complex mappings achievable where custom classes can be specified in your mapping as converters or resolvers.  Wire this all up with dependency injection and you've gotta a mean combination.

Here's the sample project, enjoy!

Sample Project

3 comments:

  1. If you are mostly keeping the property names the same and don't need a custom configuration between two classes (which AutoMapper is really good at!) then I usually use ValueInjecter (http://valueinjecter.codeplex.com/), which I find to be amazing and more terse than AutoMapper (plus you don't have to do the static registration for anything you want to map!).

    ReplyDelete
  2. Thanks a lot Robert, flexible and easy to use, also like the fact that you don’t need to specify any registration for mappings. Definitely a nice alternative depending on your requirements!

    ReplyDelete
  3. Hi Robert & Brian. Yes, automapper is a great way of making life and coding easier and simpler. Depending on the structure of the project, automapper works great mapping between the domain / service and data layer as well, and not just for the domain and view models with MVC. The domain & service layer can be completely created with a T4 template. That's your standard CRUD, and with Unity as you mentioned before, no more unnecessary "instantiasion".If such a word exists.

    ReplyDelete