More with Discovery, Day 4


Previously, we looked at configuring discovery on the server. What about the client? To discover from the client, we use a class named DiscoveryClient. DiscoveryClient implements the WS-Discovery protocol. Discovery is typically done over UDP because UDP allows for endpoints to broadcast a message.

The client uses a FindCriteria instance. In our case, we will ask for discovery to give us the metadata exchange endpoints that have definitions for ITest. Upon finding 1 of these, or timing out, we will resolve the metadata exchange endpoint and ask for information about the endpoint. If at least one of those is found (which it should be but it may disappear in between the first request and this one), extract the ITest information and create an ITest ChannelFactory using the discovered binding and endpoint. Sample code looks exactly like this:

// Create a client to find ITest instance. Return as soon as
// 1 is found.
var discoveryClient = new DiscoveryClient(new UdpDiscoveryEndpoint());
var criteria = FindCriteria.
  CreateMetadataExchangeEndpointCriteria(typeof (ITest));
criteria.MaxResults = 1;
var findResponse = discoveryClient.Find(criteria);
discoveryClient.Close();
if (findResponse.Endpoints.Count > 0)
{
  // Resolve the metadata for the first address.
  // Return the binding and address information.
  var endpoints = MetadataResolver.Resolve(typeof (ITest),
    findResponse.Endpoints[0].Address);
  if (endpoints.Count > 0)
  {
    // Create a factory based on the binding and address information
    // we received from the metadata endpoint.
    var factory = new ChannelFactory<ITest>(endpoints[0].Binding,
      endpoints[0].Address);
    var channel = factory.CreateChannel();

    // Call the add function
    Console.WriteLine(channel.Add(3, 4));
    factory.Close();
  }
}

The above code will fail if authentication credentials other than Windows or anonymous are required. But, if you use standard windows authentication on the service (or nothing) this works well. Discovery is well suited to intranet scenarios, because things like Windows identities and authentication are already in use.

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: