Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should 'CreateMap' statements go?

I frequently use AutoMapper to map Model (Domain) objects to ViewModel objects, which are then consumed by my Views, in a Model/View/View-Model pattern.

This involves many 'Mapper.CreateMap' statements, which all must be executed, but must only be executed once in the lifecycle of the application.

Technically, then, I should keep them all in a static method somewhere, which gets called from my Application_Start() method (this is an ASP.NET MVC application).

However, it seems wrong to group a lot of different mapping concerns together in one central location.

Especially when mapping code gets complex and involves formatting and other logic.

Is there a better way to organize the mapping code so that it's kept close to the ViewModel that it concerns?

(I came up with one idea - having a 'CreateMappings' method on each ViewModel, and in the BaseViewModel, calling this method on instantiation. However, since the method should only be called once in the application lifecycle, it needs some additional logic to cache a list of ViewModel types for which the CreateMappings method has been called, and then only call it when necessary, for ViewModels that aren't in that list.)

like image 870
Jonathan Avatar asked May 23 '10 13:05

Jonathan


1 Answers

If you really don't want to use a bootstrapper, then at least a static constructor is an easy way of ensuring your CreateMap is called at most once. (With less messing around and more thread proof than Jonathon's answer.)

public class AccountController : Controller 
{
    static AccountController()
    {
        Mapper.CreateMap<Models.User, ViewModels.UserProfile>();
        Mapper.CreateMap<Models.User, ViewModels.ChangePassword>();
    }
}
like image 93
Buh Buh Avatar answered Mar 01 '23 13:03

Buh Buh