我应该在哪里创建AutoMapper映射?

时间:2012-10-07 07:36:24

标签: .net asp.net-mvc automapper

我目前有一个方法RegisterMaps,可以从Application_Start调用。

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

我还有一个MappedViewModel基类,我的大多数视图模型都来自:

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

现在在RegisterMaps中维护一长串映射会给我带来一些摩擦。我正在考虑将地图创建委托给MappedViewModel中的静态构造函数。我可以安全地执行此操作,即它是否会对性能产生负面影响,还是有任何其他原因不能更多OO并让每个映射类创建自己的地图?

1 个答案:

答案 0 :(得分:1)

对于将一种类型映射到另一种类型的东西,它属于两种类型构造函数中的哪一种?

我对你当前的方法采用了类似的方法,除了我将每个映射放在自己的AutoMapper配置文件中,使用反射来查找它们并初始化它们。

通常我更进一步,不要使用AutoMapper的静态引用,它看起来有点像这样

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));
    }
}       
相关问题