1

我目前有一个RegisterMapsApplication_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. 我可以安全地做到这一点,即它会对性能产生负面影响,还是有任何其他理由不做更多的面向对象并让每个映射类创建自己的映射?

4

1 回答 1

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));
    }
}       
于 2012-10-07T08:31:33.547 回答