1

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?

ProfK
  • 49,207
  • 121
  • 399
  • 775

1 Answers1

1

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));
    }
}       
Betty
  • 9,109
  • 2
  • 34
  • 48
  • I'm afraid your code is a bit over my head. I assume your Bind and related calls are Ninject specific, and I have absolutely zero Ninect knowledge. – ProfK Oct 08 '12 at 06:20
  • I highly recommend learning dependency injection if you don't already know it. Yes those are ninject bindings, it's my di library of choice, you should play around and find one you like. – Betty Oct 08 '12 at 06:50
  • The main take away point of my code wasn't the ninject bit, it was the using automapper profiles and loading them via reflection instead of manually. – Betty Oct 08 '12 at 06:51
  • http://stackoverflow.com/a/3618359/629083 is a similar answer that uses plain reflection instead of ninject. – Betty Oct 08 '12 at 06:53