4

當您在MVC中創建控制器時,您不必爲其進行任何其他註冊。增加區域也一樣。只要你的global.asax有一個AreaRegistration.RegisterAllAreas()調用,就不需要額外的設置。自動發現自動映射器配置

使用AutoMapper,我們必須使用某種CreateMap<TSource, TDestination>調用來註冊映射。人們可以通過靜態Mapper.CreateMap或者從AutoMapper.Profile類派生,重寫Configure方法,並從那裏調用CreateMap來明確地做這些。

在我看來,像一個應該能夠掃描程序集的類擴展從Profile像MVC掃描的類從Controller延伸。有了這種機制,不應該僅僅通過創建一個派生自的類來創建映射?是否存在任何這樣的庫工具,或者是否有內置於automapper的東西?

回答

9

我不知道這樣的工具存在,但是寫一個應該是相當簡單:

public static class AutoMapperConfiguration 
{ 
    public static void Configure() 
    { 
     Mapper.Initialize(x => GetConfiguration(Mapper.Configuration)); 
    } 

    private static void GetConfiguration(IConfiguration configuration) 
    { 
     var assemblies = AppDomain.CurrentDomain.GetAssemblies(); 
     foreach (var assembly in assemblies) 
     { 
      var profiles = assembly.GetTypes().Where(x => x != typeof(Profile) && typeof(Profile).IsAssignableFrom(x)); 
      foreach (var profile in profiles) 
      { 
       configuration.AddProfile((Profile)Activator.CreateInstance(profile)); 
      } 
     } 
    } 
} 

,然後在Application_Start,你可以自動裝配:

AutoMapperConfiguration.Configure(); 
+1

代碼+1。你是不是指'.Where(x => x => x!= typeof(...',或'.Where(x => x!= typeof(...'? – danludwig 2012-07-30 15:31:45

2

由於輕微改善來自@Darin Dimitrov的回答,在AutoMapper 5中,您可以給它一個組件列表以便像這樣掃描:

//--As of 2016-09-22, AutoMapper blows up if you give it dynamic assemblies 
var assemblies = AppDomain.CurrentDomain.GetAssemblies() 
        .Where(x => !x.IsDynamic); 
//--AutoMapper will find all of the classes that extend Profile and will add them automatically  
Mapper.Initialize(cfg => cfg.AddProfiles(assemblies));