A lot of developers are seeing the wisdom in using AutoMapper to cut out the unpleasant “middle-man” of view-model design – converting Models into ViewModels.
Of course, the mappings must first be created, and once-per-application thank you. And here arises the question: do we keep the Mappings where we should - in the vicinity of the code they concern, or where we must – the Application_Begin() method of our Global class?
Personally I’d prefer the former.
So then the challenge is, how do we make sure the CreateMapping() statements are called once per application, but are still stored nearby the code they concern?
Here’s my solution (I also posted it on StackOverflow):
I add some logic to the constructor of my BaseController, which runs the ‘CreateMappings’ method, but only once per Controller Type:
public abstract class BaseController : Controller
{
public BaseController()
{
if (!controllersWithMappingsCreated.Contains(GetType()))
{
CreateMappings();
controllersWithMappingsCreated.Enqueue(GetType());
}
}
protected virtual void CreateMappings() { }
}
Then, in each concrete controller, I use CreateMappings to declare the mappings for all the Models/ViewModels relevant to that controller.
public class AccountController : BaseController
{
public AccountController() : base() { }
protected override void CreateMappings()
{
Mapper.CreateMap<Models.User, ViewModels.UserProfile>();
Mapper.CreateMap<Models.User, ViewModels.ChangePassword>();
}
}
Now I can simply override CreateMappings() in any controller class I wish, and declare only those mappings that concern the behavior of that controller.
Since I try to limit the number of concerns each controller deals with, I’m confident that none of the CreateMappings().




