2012-10-07 74 views
1

我目前有一個從Application_Start調用的方法RegisterMaps我應該在哪裏創建我的AutoMapper映射?

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。我能否安全地做到這一點,即是否會對性能產生負面影響?還是有其他理由不再需要面向對象並讓每個映射類創建自己的地圖?

回答

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)); 
    } 
}  
+0

恐怕你的代碼是有點在我頭上。我假設你的綁定和相關的調用是Ninject特定的,並且我絕對沒有Ninect的知識。 – ProfK

+0

如果你還不知道,我強烈建議學習依賴注入。是的,這些都是ninject綁定,它是我選擇的二元庫,你應該玩耍並找到你喜歡的一個。 – Betty

+0

我的代碼的主要拿走點不是ninject位,它是使用automapper配置文件並通過反射而不是手動加載它們。 – Betty

相關問題