Where to place AutoMapper.CreateMaps?

Shawn Mclean picture Shawn Mclean · Jul 26, 2011 · Viewed 93.4k times · Source

I'm using AutoMapper in an ASP.NET MVC application. I was told that I should move the AutoMapper.CreateMap elsewhere as they have a lot of overhead. I'm not too sure how to design my application to put these calls in just 1 place.

I have a web layer, service layer and a data layer. Each a project of its own. I use Ninject to DI everything. I'll utilize AutoMapper in both web and service layers.

So what are your setup for AutoMapper's CreateMap? Where do you put it? How do you call it?

Answer

RPM1984 picture RPM1984 · Jul 26, 2011

Doesn't matter, as long as it's a static class. It's all about convention.

Our convention is that each "layer" (web, services, data) has a single file called AutoMapperXConfiguration.cs, with a single method called Configure(), where X is the layer.

The Configure() method then calls private methods for each area.

Here's an example of our web tier config:

public static class AutoMapperWebConfiguration
{
   public static void Configure()
   {
      ConfigureUserMapping();
      ConfigurePostMapping();
   }

   private static void ConfigureUserMapping()
   {
      Mapper.CreateMap<User,UserViewModel>();
   } 

   // ... etc
}

We create a method for each "aggregate" (User, Post), so things are separated nicely.

Then your Global.asax:

AutoMapperWebConfiguration.Configure();
AutoMapperServicesConfiguration.Configure();
AutoMapperDomainConfiguration.Configure();
// etc

It's kind of like an "interface of words" - can't enforce it, but you expect it, so you can code (and refactor) if necessary.

EDIT:

Just thought I'd mention that I now use AutoMapper profiles, so the above example becomes:

public static class AutoMapperWebConfiguration
{
   public static void Configure()
   {
      Mapper.Initialize(cfg =>
      {
        cfg.AddProfile(new UserProfile());
        cfg.AddProfile(new PostProfile());
      });
   }
}

public class UserProfile : Profile
{
    protected override void Configure()
    {
         Mapper.CreateMap<User,UserViewModel>();
    }
}

Much cleaner/more robust.