Sunday, 26 September 2010

Playing with AutoMapper

In my current role we have come across a requirement to map message objects to more complex domain entities.  As anyone that has done this previously will quickly tell you, manually writing code to do this is very boring and repetitive.  With very limited time and resources, that effort could be better spent elsewhere on the project.  As it seemed very simple to set up and start using we’ve decided to use AutoMapper.

Configuring / Using
Setting up a basic mapper is as simple as:
Mapper.CreateMap<Source,Target>();
var target = Mapper.Map<Source,Target>(source);
The call to CreateMap only needs to be made once for the duration of the AppDomain, calls to Map are then made as needed.
As was as direct property name mapping several other more complex mappings are provided “out of the box”.  This includes flattening properties of child objects into named properties in the target object.   AutoMapper also provides several different methods to provide custom mappings either inline in the form:

Mapper.CreateMap<CalendarEvent, CalendarEventForm>()

.ForMember(dest => dest.EventDate, opt => opt.MapFrom(src => src.EventDate.Date))

.ForMember(dest => dest.EventHour, opt => opt.MapFrom(src => src.EventDate.Hour))

.ForMember(dest => dest.EventMinute, opt => opt.MapFrom(src => src.EventDate.Minute));
Or using custom formatting classes in the form:


  1. Mapper.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter());
  2. public class DateTimeTypeConverter : ITypeConverter<string, DateTime>
  3. {
  4.     public DateTime Convert(string source)
  5.     {
  6.         return System.Convert.ToDateTime(source);
  7.     }
  8. }


Performance
Initial tests have thrown up no surprises; the flexibility that Automapper provides does come with some overhead – but in most cases I’m sure that the performance is going to be fine for the project in question.  Being able to quickly map messages to domain objects and move on is going to improve the speed in which we can develop the project.  If problems are encountered once the code base is live, there is nothing to stop the areas in question being re-investigated and/or rolled back to manual mappings.


del.icio.us Tags:

No comments:

Post a Comment