如何:使用 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."));
          }
      }
    }
    

另请参见

概念

元数据