2012-11-02 5 views
2

왜이왜 Automappers ValueResolver를 사용합니까?

Mapper.CreateMap<MyObject, AnotherObject>(). 
ForMember(x => x.DateAsString, m => m.ResolveUsing<StringToDateTimeFormatter>()); 

private class StringToDateTimeFormatter : ValueResolver<DateTime, string> 
{ 
    protected override string ResolveCore(DateTimesource) 
    { 
     return source.ToString("yyyy-MM-dd"); 
    } 

} 

당신이 할 수있는이

Mapper.CreateMap<MyObject, AnotherObject>(). 
ForMember(x => x.DateAsString, m => m.MapFrom(x => x.Date.ToString("yyy-MM-dd"))); 

을 ??? 여기에 업데이트

을위한 분명히

답변

4

... 더 복잡한 비즈니스 로직

Mapper.CreateMap<MyObject, AnotherObject>(). 
ForMember(x => x.DateAsString, m => m.MapFrom(n => MyMethod(n.DateAsString))); 

    private object MyMethod(string dateTime) 
    { 
     if(!MyDomainObjectIsValid(dateTime)) 
     { 
      throw new MyValidationException(); 
     } 

     // do more stuff 
    } 

나는 여전히 ValueResolver에 대한 필요성이 표시되지 않는 작업을 수행하는 방법에 대한 예제가 당신의 예를 들어 MapFrom을 사용하는 것이 더 합리적입니다. 보다 복잡한 경우 ValueResolvers가 필요합니다. 예를 들어, 일부 유효성 검사를 수행하고 그에 따라 예외를 throw해야하는 경우.

EDIT ValueResolvers는 대상 유형 및 값에 대한 액세스를 제공합니다. 여기에 작은 예가 있습니다. 매핑이 더 복잡 할 때

public class FakeResolver : IValueResolver 
{ 
    public ResolutionResult Resolve(ResolutionResult source) 
    { 
     if (source.Context.DestinationType == typeof(string) && source.Context.DestinationValue == "test") 
      throw new Exception(); 
     return source; 
    } 
} 
+0

정확히, 나는 비즈니스 오브젝트 많은 일을 할 수있는 값의 해결을 사용 - 간단한 람다 구문이 경우에서 유용하지 않습니다에 대한 – Charleh

+0

감사합니다 (여러 정적 메소드 등을 호출하는) 당신의 댓글. 나는 네가 맞다고 확신하지만 아직 만족하지는 않는다. 원래 질문에서 내가 추가 한 예를 보아라. ValueResolver를 사용하지 않고 비즈니스 운영을 수행하고 예외를 throw 할 수 있습니다. ValueResolver를 사용해야하는 예제를 보여줄 수 있습니까? – FatAlbert

+0

그에 따라 답변이 업데이트되었습니다. – k0stya

관련 문제