ProfK
ProfK

Reputation: 51064

Where should I create my AutoMapper mappings?

I currently have a method RegisterMaps that is called from Application_Start.

public static class AutoMapperRegistrar
{
    public static void RegisterMaps()
    {
        Mapper.CreateMap<Employee, EmployeeEditModel>();
        Mapper.CreateMap<Employee, EmployeeCreateModel>();
    }
}

I also have a MappedViewModel base class that most of my view models derive from:

public class MappedViewModel<TEntity>: ViewModel
{
    public virtual void MapFromEntity(TEntity entity)
    {
        Mapper.Map(entity, this, typeof(TEntity), GetType());
    }
}

Now maintaining a long list of mappings in RegisterMaps creates a bit of friction for me. I am thinking of delegating the map creation to a static constructor in MappedViewModel. Can I do this safely, i.e. will it negatively affect performance, or is there any other reason to not be more OO and let each mapped class create its own map?

Upvotes: 1

Views: 813

Answers (1)

Betty
Betty

Reputation: 9189

For something that maps one type to another, which of the two types constructor does it belong in?

I have a similar approach to your current method, except that I put each mapping in its own AutoMapper profile, using reflection to find them all and initialize them.

Typically i go one step further and don't use the static reference to AutoMapper, it ends up looking a bit like this

Bind<ITypeMapFactory>().To<TypeMapFactory>();
Bind<ConfigurationStore>().ToSelf().InSingletonScope();
Bind<IConfiguration>().ToMethod(c => c.Kernel.Get<ConfigurationStore>());
Bind<IConfigurationProvider>().ToMethod(c => c.Kernel.Get<ConfigurationStore>());
Bind<IMappingEngine>().To<MappingEngine>();

//Load all the mapper profiles
var configurationStore = Kernel.Get<ConfigurationStore>();
foreach (var profile in typeof(AutoMapperNinjectModule).Assembly.GetAll<Profile>())
{
    configurationStore.AddProfile(Kernel.Get(profile) as Profile);
}



public class AccountViewModelProfile : Profile
{
    protected override void Configure()
    {
        CreateMap<Account, AccountListItemViewModel>()
            .ForMember(d => d.AccountType, opt => opt.MapFrom(s => s.GetType().Name));
    }
}       

Upvotes: 1

Related Questions