0

ジェネリック WCF サービス呼び出しユーティリティを作成しようとしていますが、ジェネリック、デリゲート、およびラムダに関する知識が最後のハードルで失敗しています。

WCF Web サービスを呼び出す際の認証と予期処理をカプセル化して、インターフェイス、要求、および応答クラスだけで Web サービスを利用できるようにしたいと考えています。

実行したいメソッド名を渡す方法がわかりません - 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;
}
4

1 に答える 1

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;
    }
于 2011-04-27T08:45:49.940 に答える