2014-06-16 2 views
0

그래서 .. 일부 WCF 서비스가 있고 이러한 wcf 서비스는 리플렉션으로 호출됩니다. 호출 된 각 서비스마다 다른 객체로 배열을 반환합니다.반사, 개체 컬렉션을 가져 와서 원하는 개체 형식으로 변환하십시오.

내 임무는 이러한 개체를 가져 와서 내 BusinessObjects에있는 개체에 매핑하는 것입니다. 그들은 T에 의해 정의됩니다.

public virtual IQueryable<T> GetAll() 
    { 
     //Methods retreives an array of objects. 
     var blah = _getAllFromWcf.Invoke(_rawServiceObject, new object[] {}); 
     //Says that this is an array 
     var blahsType = blah.GetType(); 
     //This is the type of object in the array 
     var blahsElementType = blahsType.GetElementType(); 
     //This is where i want to convert the element in the array to the type T so that i can return it in the IQueryable<T> 
     blah.MapCollection<'The type of element in blah', T>(); 

     return null; 
    } 

blah.MapCollection <는> AutoMapper을 사용하여리스트 내의 요소 변환 내가 만든 확장 방법.

MapCollection은 당연히 작동하지 않습니다. 왜냐하면이 시점에서 객체의 유형을 알지 못하기 때문에 blah가 배열이고 '쉼표로 요소 유형'이 작동하지 않는다는 것을 이해하지 못하기 때문입니다. ....

누구든지 지침이 있습니까?

+1

리플렉션 및 Invoke MapCollection 메서드를 계속 사용할 수 있습니다. http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method. – qbik

+0

좋은 생각 ..하지만 여전히 IQueryable로 컬렉션을 반환해야합니다 ... 그 어떤 힌트? –

답변

0

나는 당신이 그것에 의견이 있으면 .. 이런 식으로 일을하거나 그냥 일을 더 나은 방법이 결국, 주시기 바랍니다 의견을 :)

public virtual IQueryable<T> GetAll() 
    { 
     //Methods retreives an array of objects. 
     var collectionFromWcfService = _getAllFromWcf.Invoke(_rawServiceObject, new object[] {}); 
     //Says that this is an array 
     var typeOfArray = collectionFromWcfService.GetType(); 
     //This is the type of object in the array 
     var elementTypeInArray = typeOfArray.GetElementType(); 

     MethodInfo method = typeof(Extensions).GetMethod("MapCollectionWithoutExtension"); 
     MethodInfo generic = method.MakeGenericMethod(elementTypeInArray,typeof(T)); 

     var convertedListOfObjects = (List<T>)generic.Invoke(this, new []{ collectionFromWcfService }); 

     return convertedListOfObjects.AsQueryable(); 
    } 

내가 AutoMapper 구현을 숨겨하고 다른 도구에 의해 변환을 지금 수있는이 솔루션을 무료, 또는 수동으로 내가 시간에 나중에 그것을 필요로하는 경우.

1

확장 메소드는 런타임시이를 알 수 없기 때문에 유형을 제네릭 매개 변수로 사용할 수 없습니다. 확장자에 Type 유형의 일반 매개 변수로 전달해야합니다. AutoMapper는 유형 정보를 일반 매개 변수로 전달하는 메소드도 제공합니다.

당신은 또한 단지 AutoMapper로 매핑하는 LINQ를 사용할 수 있습니다

:

blah.Select(item => Mapper.Map(item, item.GetType(), typeof(T)) as T) 
+0

하지만 Automapper가 수신하는 객체가 목록/배열/일종의 ienumerable이라고 말할 수 있어야합니다. 그렇지 않은 경우 단일 객체로 매핑하려고하면 작동하지 않습니다. 내가 그랬어? –

+0

@ BjørnØyvindHalvorsen 필연적으로 컨테이너 변환을 직접 수행 할 수 있으며 자동 매퍼가 항목 대 항목 변환에 대해 걱정할 필요가 없습니다. 내 편집을 참조하십시오. – nvoigt

+0

아주 좋습니다! 고마워.............. 그것을 조금하면서 끝내게되었다. ... .. 나는 제안되었던 나의 솔루션을 게시 할 것이다. :) –

관련 문제