2012-04-19 7 views
4

현재 AutoMapper (최신 .NET 3.5 버전)를 실험 중입니다. AutoMapper를 작동 시키려면 한 객체에서 다른 객체로 매핑하는 방법에 대한 구성 정보를 제공해야합니다.(GAC) 클래스 라이브러리에서 Automapper 초기화

Mapper.CreateMap<ContactDTO, Contact>(); 
Mapper.CreateMap<Contact, ContactDTO>(); 

응용 프로그램, 서비스, 웹 사이트가 시작될 때이 작업을 수행해야합니다. (global.asax 등 사용)

문제는, 나는 GAC'd DLL에서 Automaper를 사용하여 LINQ2SQL 객체를 해당 BO 객체에 매핑합니다. .CreateMap <> 세부 사항을 지정하지 않아도되도록 맵 2 객체를 원할 때마다이 구성을 지정할 수 있습니까? 가능하면?

+2

왜'Mapper'도 정적이기 때문에 GAC 파일에서'Initialize' 메쏘드로 정적 클래스를 사용하지 않으시겠습니까? 앱을 시작할 때 한 번만 호출하십시오. –

+0

문제는 많은 다른 프로젝트에서 사용되는 데이터 액세스 DLL에서 이것을 사용하고 있으므로 매퍼 초기화에 대한 실제 단일 진입 점이 없다는 것입니다. – stvn

+1

C++과 달리 정적 생성자는 어셈블리가로드 될 때가 아니라 필요할 때 실행됩니다. 라이브러리에 대한 진입 점이 있으면 초기화 할 해당 유형의 정적 생성자를 만듭니다. 그렇지 않으면 [해킹 같은] (http://einaregilsson.com/module-initializers-in-csharp/) –

답변

0

나는 해결책이 AutoMapper 자체에 있다고 생각한다.

AutoMapper 프로필을 사용하고 시작할 때 등록하십시오.

프로필에 의존성이 필요하지 않은 경우 IOL 컨테이너는 필요하지 않습니다.

/// <summary> 
///  Helper class for scanning assemblies and automatically adding AutoMapper.Profile 
///  implementations to the AutoMapper Configuration. 
/// </summary> 
public static class AutoProfiler 
{ 
    public static void RegisterReferencedProfiles() 
    { 
     AppDomain.CurrentDomain 
      .GetReferencedTypes() 
      .Where(type => type != typeof(Profile) 
       && typeof(Profile).IsAssignableFrom(type) 
       && !type.IsAbstract) 
      .ForEach(type => Mapper.Configuration.AddProfile(
       (Profile)Activator.CreateInstance(type))); 
    } 
} 

그들은 단지이 예와 같이 프로파일을 구현 :

public class ContactMappingProfile : Profile 
{ 
    protected override void Configure() 
    { 
     this.CreateMap<Contact, ContactDTO>(); 
     this.CreateMap<ContactDTO, Contact>(); 
    } 
} 

하지만 당신의 프로필은 AutoMapper에 대한 추상화를 만들고 단지를 등록하기 전에 모든 프로필을 등록 할 수 있습니다 해결해야 의존성이있는 경우 추상화 - IObjectMapper -이 같은 싱글로 :

public class AutoMapperModule : Module 
{ 
    protected override void Load(ContainerBuilder builder) 
    { 
     base.Load(builder); 

     // register all profiles in container 
     AppDomain.CurrentDomain 
      .GetReferencedTypes() 
      .Where(type => type != typeof(Profile) 
       && typeof(Profile).IsAssignableFrom(type) 
       && !type.IsAbstract) 
      .ForEach(type => builder 
       .RegisterType(type) 
       .As<Profile>() 
       .PropertiesAutowired()); 

     // register mapper 
     builder 
      .Register(
       context => 
       { 
        // register all profiles in AutoMapper 
        context 
         .Resolve<IEnumerable<Profile>>() 
         .ForEach(Mapper.Configuration.AddProfile); 
        // register object mapper implementation 
        return new AutoMapperObjectMapper(); 
       }) 
      .As<IObjectMapper>() 
      .SingleInstance() 
      .AutoActivate(); 
    } 
} 

이후이 최고의 approac을 보였다 도메인의 추상적 내 모든 기술 나를위한 h.

이제 코드를 작성해주세요.

PS-이 코드는 일부 헬퍼와 확장 기능을 사용할 수 있지만 핵심 요소입니다.

관련 문제