次の方法で共有


方法 : MetadataResolver を使用してバインディング メタデータを動的に取得する

ここでは、MetadataResolver クラスを使用してバインディング メタデータを動的に取得する方法を示します。

バインディング メタデータを動的に取得するには

  1. メタデータ エンドポイントのアドレスを持つ EndpointAddress オブジェクトを作成します。

    EndpointAddress metaAddress
      = new EndpointAddress(new   Uri("https://localhost:8080/SampleService/mex"));
    
  2. サービス型とメタデータ エンドポイント アドレスを渡して、Resolve を呼び出します。これにより、指定したコントラクトを実装したエンドポイントのコレクションが返されます。メタデータからはバインディング情報のみがインポートされます。コントラクト情報はインポートされません。提供されたコントラクトが代わりに使用されます。

    ServiceEndpointCollection endpoints = MetadataResolver.Resolve(typeof(SampleServiceClient),metaAddress);
    
  3. これで、サービス エンドポイントのコレクションを反復処理して必要なバインディング情報を抽出できます。次のコードは、エンドポイントを反復処理し、現在のエンドポイントに関連付けられたバインディングとアドレスを渡すサービス クライアント オブジェクトを作成し、そのサービスでメソッドを呼び出します。

    foreach (ServiceEndpoint point in endpoints)
    {
       if (point != null)
       {
          // Create a new wcfClient using retrieved endpoints.
          using (wcfClient = new SampleServiceClient(point.Binding, point.Address))
          {
             Console.WriteLine(
               wcfClient.SampleMethod("Client used the "
               + point.Address.ToString() + " address."));
          }
      }
    }
    

関連項目

概念

メタデータ