문제

CreateChannel 메서드를 호출하기 위해 형식이 필요한 ChannelFactory를 사용하여 WCF를 프로그래밍하고 있습니다.예를 들어:

IProxy proxy = ChannelFactory<IProxy>.CreateChannel(...);

내 경우에는 라우팅을 수행 중이므로 내 채널 팩터리가 어떤 유형을 사용할지 알 수 없습니다.유형을 결정하기 위해 메시지 헤더를 구문 분석할 수 있지만 Type의 인스턴스가 있더라도 ChannelFactory가 일반 유형을 기대하는 곳을 전달할 수 없기 때문에 거기에서 벽돌 벽에 부딪혔습니다.

이 문제를 매우 간단한 용어로 다시 설명하는 또 다른 방법은 다음과 같은 작업을 시도하는 것입니다.

string listtype = Console.ReadLine(); // say "System.Int32"
Type t = Type.GetType( listtype);
List<t> myIntegers = new List<>(); // does not compile, expects a "type"
List<typeof(t)> myIntegers = new List<typeof(t)>(); // interesting - type must resolve at compile time?

C# 내에서 활용할 수 있는 접근 방식이 있나요?

도움이 되었습니까?

해결책

당신이 찾고있는 것은 MakeGenericType입니다

string elementTypeName = Console.ReadLine();
Type elementType = Type.GetType(elementTypeName);
Type[] types = new Type[] { elementType };

Type listType = typeof(List<>);
Type genericType = listType.MakeGenericType(types);
IProxy  proxy = (IProxy)Activator.CreateInstance(genericType);

따라서 당신이 하고 있는 일은 일반적인 "템플릿" 클래스의 유형 정의를 얻은 다음 런타임 구동 유형을 사용하여 유형의 특수화를 구축하는 것입니다.

다른 팁

Ayende의 이 게시물을 살펴보세요. WCF, 모의 및 IoC:어머!.하단 근처에는 도움이 될 GetCreationDelegate라는 메서드가 있습니다.기본적으로 다음을 수행합니다.

string typeName = ...;
Type proxyType = Type.GetType(typeName);

Type type = typeof (ChannelFactory<>).MakeGenericType(proxyType);

object target = Activator.CreateInstance(type);

MethodInfo methodInfo = type.GetMethod("CreateChannel", new Type[] {});

return methodInfo.Invoke(target, new object[0]);

질문은 다음과 같습니다.당신은 ~ 정말 특정 사례에 정확한 계약 유형으로 채널을 만들어야 합니까?

라우팅을 수행하고 있으므로 일반적인 채널 모양을 간단히 처리할 수 있는 가능성이 매우 높습니다.예를 들어 단방향 메시지를 라우팅하는 경우 다음과 같이 메시지를 보내는 채널을 만들 수 있습니다.

ChannelFactory<IOutputChannel> factory = new ChannelFactory<IOutputChannel>(binding, endpoint);
IOutputChannel channel = factory.CreateChannel();
...
channel.SendMessage(myRawMessage);

양방향 서비스로 전송해야 하는 경우 대신 IRequestChannel을 사용하세요.

라우팅을 수행하는 경우 일반적으로 일반 채널 형태(외부에 대한 일반적인 포괄 서비스 계약 포함)를 처리하고 보내는 메시지가 올바른지 확인하는 것이 훨씬 쉽습니다. 헤더와 속성.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top