Where should 'CreateMap' statements go?

Posted by jonathanconway on Stack Overflow See other posts from Stack Overflow or by jonathanconway
Published on 2010-05-23T13:29:12Z Indexed on 2010/05/23 13:30 UTC
Read the original article Hit count: 485

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.)

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about automapper