2011-04-26 5 views
0

일반 WCF 서비스 호출자 유틸리티를 만들려고하고 있지만 제네릭, 델리게이트 및 람다에 대한 지식이 최종 장애물에서 실패하고 있습니다.일반 WCF 서비스 호출자 생성 - 일반, 대리인 및 람다

인터페이스, 요청 및 응답 클래스만으로 웹 서비스를 사용할 수 있도록 내 WCF 웹 서비스를 호출하는 인증 및 제외 처리를 캡슐화하고 싶습니다.

실행하려는 메서드 이름을 전달할 수있는 방법을 이해할 수 없습니다 - Func <> 경로를 시도했지만 아래 구현 한 것과 재귀 오류가 발생하여 혼란스러워지고 있습니다. 나는 하드 코딩 된 문자열/반사 경로 중 하나를 사용하지 않는 것을 선호한다 - 나는 이것이 강력하게 유형화 된 클래스가되기를 바란다.

도와주세요!

public static TResponse Invoke<TService, TRequest, TResponse>(TRequest request, Func<TService, TRequest, TResponse> methodToExecute, string endpointConfigurationName) where TResponse : class 
{ 
    ChannelFactory<TService> channel = new ChannelFactory<TService>(endpointConfigurationName); 

    // attach auth credentials 
    channel.Credentials.UserName.UserName = "myUserName"; 
    channel.Credentials.UserName.Password = "myPassword"; 

    // create a proxy for the channel 
    TService proxy = channel.CreateChannel(); 
    TResponse response; 

    try 
    { 
    response = methodToExecute(proxy, request); 
    channel.Close(); 
    } 
    catch 
    { 
    // abort or close in a fail-safe manner 
     if (channel.State == CommunicationState.Faulted) 
     { 
     channel.Abort(); 
     } 
     else 
     { 
     channel.Close(); 
     } 

     throw; 
    } 

    return response; 
} 

답변

1

것은 여기 내 시도이다 주셔서 감사합니다. 내 버전의 매개 변수로 요청 유형이 없습니다. 나는 당신이 그것을 사용하기를 기대하는 방법을 보여줍니다. (당신은 당신의 호출 방법을 보여주지 않았지만, 문제는 호출 자체에있는 것이 아니라 메소드에 있다고 생각합니다.)

private class Response {} 

    private interface IService 
    { 
     Response MyMethod(object i); 
    } 

    public static void Foo() 
    { 
     object request = 1; 
     Response response = Invoke((IService service) => service.MyMethod(request), "endpoint"); 
    } 

    public static TResponse Invoke<TService, TResponse>(Func<TService, TResponse> methodToExecute, string endpointConfigurationName) where TResponse : class 
    { 
     ChannelFactory<TService> channel = new ChannelFactory<TService>(endpointConfigurationName); 

     // attach auth credentials 
     channel.Credentials.UserName.UserName = "myUserName"; 
     channel.Credentials.UserName.Password = "myPassword"; 

     // create a proxy for the channel 
     TService proxy = channel.CreateChannel(); 
     TResponse response; 

     try 
     { 
      response = methodToExecute(proxy); 
      channel.Close(); 
     } 
     catch 
     { 
      // abort or close in a fail-safe manner 
      if (channel.State == CommunicationState.Faulted) 
      { 
       channel.Abort(); 
      } 
      else 
      { 
       channel.Close(); 
      } 

      throw; 
     } 

     return response; 
    } 
+1

우수 - 도움 주셔서 감사합니다. 너는 나의 하루를 구했다! – AlterEgo