4

MVC에서 컨트롤러를 만들 때 추가 등록을 할 필요가 없습니다. 영역을 추가하는 경우에도 마찬가지입니다. global.asax에 AreaRegistration.RegisterAllAreas() 호출이 있으면 추가 설정이 필요하지 않습니다.자동 검색 구성 자동 검색

AutoMapper를 사용하면 일종의 CreateMap<TSource, TDestination> 호출을 사용하여 매핑을 등록해야합니다. 정적 인 Mapper.CreateMap을 사용하거나 AutoMapper.Profile 클래스에서 파생되어 Configure 메서드를 재정의하고 CreateMap을 호출하여 명시 적으로이 작업을 수행 할 수 있습니다.

에서 확장되는 클래스의 MVC 검사처럼 Profile에서 확장되는 클래스의 어셈블리를 스캔 할 수 있어야합니다. 이런 종류의 메커니즘을 사용하면 Profile에서 파생되는 클래스를 생성하여 매핑을 만드는 것이 가능하지 않아야합니까? 라이브러리 도구가 존재합니까? 아니면 자동 완성 기능이 내장되어 있습니까?

답변

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 당신은 autowire하기 수 :

AutoMapperConfiguration.Configure(); 
+1

코드 +1. '.Xhere = x => x! = typeof (...','.Where (x => x! = typeof (...'? – danludwig

2

을에 약간의 개선으로 AutoMapper 5에서 @Darin Dimitrov의 답은 다음과 같이 스캔 할 어셈블리 목록을 제공 할 수 있습니다.

//--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));