Click here to Skip to main content
12,826,806 members (33,184 online)
Click here to Skip to main content
Add your own
alternative version


33 bookmarked
Posted 3 Oct 2012

WCF 4.0 Discovery

, 3 Oct 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
This article describes WCF 4.0 discovery system.

Table of Contents


In some business solutions it is required to have different type of service enabled devices which are constantly linking and sendoff to the network. That is, the runtime location of those services is dynamic and continuously shifting. To connect to those services, clients require determining the runtime location of those service endpoints dynamically. Windows Communication Foundation (WCF) offers support to enable those services to be discoverable at runtime using the WS-Discovery protocol. In this article I will describe the WCF 4.0 Discovery System. 

Underlying Technique

Discovery depends on the User Datagram Protocol (UDP). UDP is a connectionless protocol, and there is no direct connection required between the client and server. The client usages UDP to broadcast finding requests for any endpoint supporting a specified contract type. The discovery endpoints that support this contract will receive the request. The implementation of the discovery endpoint responds back to the client with the address of the service endpoints. Once the client determines the services, it invokes the service to set up call.

Simple Service Discovery

WCF services can broadcast their availability to the network using a multicast memo or to a discovery proxy server. Client applications can pursuit the network or a discovery proxy server to discovery services that encounter a set of criteria. There are two modes of service discovery Ad-hoc Discovery and Managed Discovery. In the ad-hoc discovery clients can discover services on a local subnet and in Managed discovery clients can discover services on a larger managed network through a discovery proxy.

The easiest way to enable service discovery is through the ad hoc mode. To configure the service for discovery, we need to add the standard udpDiscoveryEndpoint endpoint as well as need to enable the serviceDiscovery behavior on the service. Once udpDiscoveryEndpoint is active, clients will be able to discover it over UDP and bind to the endpoint. If the service exposes the metadataExchange endpoint, the client can discover it too and dynamically bind to the end point.

How services are getting set up?  

     <service name="Rashim.RND.AdhocDiscovery.Services.MessageService">
           <add baseAddress="http://localhost:8732/MessageService"/>

In the service section we see ,MessageService has a base address and it disclosures three endpoints. The mexEndpoint is for metadataexchange where udpDiscoveryEndpoint is for UDP discovery. There are couple of service behavior defines using default behavior. In endpoint behavior we add a behavior called endpointDiscovery and in the endpoint discovery we add the scope. Scopes are vastly useful in modifying discovery and in adding stylish behavior. A scope is a URI that has meaning to the caller and service. The service needs to associate one or more scopes with each endpoint it’s going to publish for discovery. Clients can then discover the service based on the scope. 

How clients are getting set up?  

var discoveryClient = new DiscoveryClient(new UdpDiscoveryEndpoint());
            var findCriteria = FindCriteria.CreateMetadataExchangeEndpointCriteria(typeof(IMessageService));
            findCriteria.MaxResults = 1;
            Debug.Assert(findCriteria.Scopes != null, "findCriteria.Scopes != null");
            findCriteria.Scopes.Add(new Uri("ldap:///ou=people,o=rashim"));
            var findResponse = discoveryClient.Find(findCriteria);

            if (findResponse != null)
                    if (findResponse.Endpoints.Count > 0)
                        var endpoints = MetadataResolver.Resolve(typeof (IMessageService),
                        var factory = new ChannelFactory<imessageservice>(endpoints[0].Binding, endpoints[0].Address);
                        var channel = factory.CreateChannel();

                        Console.WriteLine("Say something and press enter");
                        var input = Console.ReadLine();
                        while (input != null && input.ToString(CultureInfo.InvariantCulture).ToLower()!="exit")
                            input = Console.ReadLine();

Here DiscoveryClient allows us to discover available services. FindCriteria is used to find IMessageService endpoints in the specified scope. Once the client has retrieved the collection of discovered endpoints, it can use one of them to actually invoke the target service. The whole thing we can also define via config file given below.  

      <endpoint contract="Rashim.RND.AdhocDiscovery.Services.IMessageService"
             endpointConfiguration="myDynamicEndpointConfig" name="discovery">


Service Announcement  

The WCF discovery feature enables mechanisms where the service broadcasts its status to all clients and provides its address. That is, each announcement contains the endpoint address, its scopes and its contract. The service host broadcasts Hello and Bye announcements when it is being online and offline. . But if the host is aborted ungracefully, no “bye” announcement is sent. Clients can listen for such announcement messages and then do necessary stuffs. This announcement services reduces the amount of probing/multicast messaging.

How services are getting set up?  

          <serviceMetadata httpGetEnabled="true"/>
              <endpoint kind="udpAnnouncementEndpoint"/>

We configure a service with an announcement endpoint by using the serviceDiscovery behavior. The serviceDiscovery behavior allows you to define a collection of announcement endpoints that will be exposed by the service. You can use the standard udpAnnouncementEndpoint for most cases. In the config file we see that announcementEndpoints add one udpAnnouncementEndpoint that will broadcast the messages when it comes online as well as offline. We also need to be aware about endpointDiscovery.It should enable to true to make a particular endpoint automatically discoverable.

How clients are getting set up? 

var announcementService = new AnnouncementService();

            announcementService.OnlineAnnouncementReceived += (sender, e) =>
                var mexContractDescrition = ContractDescription.GetContract(typeof(IMetadataExchange));
                var mexQualifiedName = new XmlQualifiedName(mexContractDescrition.Name, mexContractDescrition.Namespace);

                e.EndpointDiscoveryMetadata.ContractTypeNames.ToList().ForEach((name) =>
                                            if (mexQualifiedName != name) return;
                                            var endpoints = MetadataResolver.Resolve(typeof(IMessageServices), e.EndpointDiscoveryMetadata.Address);
                                            if (endpoints.Count <= 0) return;
                                            var factory = new ChannelFactory<IMessageServices>(endpoints[0].Binding, endpoints[0].Address);
                                            var channel = factory.CreateChannel();
                                            Console.WriteLine("\nService is online now..");
                                            var replyMessage = channel.GetMessage("Server is responding");

            announcementService.OfflineAnnouncementReceived += (sender, e) =>
                if (e.EndpointDiscoveryMetadata.ContractTypeNames.FirstOrDefault(contract => contract.Name == typeof(IMessageServices).Name) == null) return;

                Console.WriteLine("\nService says 'Good Bye'");

            using (var announecementServiceHost = new ServiceHost(announcementService))
                announecementServiceHost.AddServiceEndpoint(new UdpAnnouncementEndpoint());
                Console.WriteLine("Please enter to exit\n\n");

Clients host an AnnouncementService to listen for announcement to respond to the Hello and Bye messages. The AnnouncementService provides two event handlers: OnlineAnnouncementReceived and OfflineAnnouncementReceived. Client applications can simply host an instance of the AnnouncementService using ServiceHost and also subscribe to the OnlineAnnouncementReceived and OfflineAnnouncementReceived events.Please have a look on the code. 

Managed Discovery 

Managed discovery is needed when we want to use WS-Discovery beyond the boundaries of our local network. Managed discovery allows us to locate services no matter where they are, as long as they are registered with a discovery proxy. A discovery proxy is a standalone service that contains a repository of services. Clients can query a discovery proxy to find discoverable services that the proxy is aware of. How a proxy is populated with services is up to the implementer. 

The System.ServiceModel.Discovery namespace includes a base class to help us in building our Discovery Proxy. To implement our proxy we will have to override a number of methods provided by the System.ServiceModel.Discovery.DiscoveryProxy class.

How discovery proxy is getting set up?

var baseAddress =
               new Uri("http://localhost/demo");

           using (var host = new System.ServiceModel.ServiceHost(new DiscoveryProxyService(), baseAddress))
               host.AddServiceEndpoint(new DiscoveryEndpoint(new WSHttpBinding(), new EndpointAddress(host.BaseAddresses[0]+"/probe")){IsSystemEndpoint = false});
               host.AddServiceEndpoint(new AnnouncementEndpoint(new WSHttpBinding(), new EndpointAddress(host.BaseAddresses[0] + "/announcement")) { IsSystemEndpoint = false });
               host.Description.Endpoints.ToList().ForEach((item)=> Console.WriteLine(item.ListenUri));


               Console.WriteLine("Press enter to exit.");

In the above code portion, the host add two service endpoints, one is DiscoveryEndpoint which specifies where the client should listen for the discovery messages another one is AnnouncementEndpoint which specifies where the services should send announcement messages.The discovery proxy class that I have used in the demo project has been taken from here.

How services are getting set up?   

      <service name="Rashim.RND.ManagedDiscovery.DiscoverableService.StringService">
            <add baseAddress="http://localhost/StringService"/>

In the configuration file, there is a base address and a scope has been defined  The details of this file have been discussed in above in the simple service discovery section. 

var announcementAddress =
               new Uri("http://localhost/demo/announcement");
           var host = new System.ServiceModel.ServiceHost(typeof (StringService));

               var announcementEndpoint = new AnnouncementEndpoint(new WSHttpBinding(),
                                                                   new EndpointAddress(announcementAddress));
               var serviceDiscoveryBehavior = new ServiceDiscoveryBehavior();

               host.Description.Endpoints.ToList().ForEach((endpoint) => Console.WriteLine(endpoint.ListenUri));
               Console.WriteLine("Please enter to exit");
           catch (Exception oEx)

In the above code the host adds the ServiceDiscoveryBehavior which controls the discoverability of service endpoints and ServiceDiscoveryBehavior add AnnouncementEndpoints with the address that DiscoveryProxy exposes for announcement.

How clients are getting set up? 

var probeAddress = new Uri("http://localhost/demo/probe");
            var discoveryEndpoint = new DiscoveryEndpoint(new WSHttpBinding(), new EndpointAddress(probeAddress));
            var discoveryClient = new DiscoveryClient(discoveryEndpoint);
            var findCriteria = new FindCriteria(typeof (IStringService));

            findCriteria.Scopes.Add(new Uri("ldap:///ou=people,o=rashim"));

            var findResponse = discoveryClient.Find(findCriteria);

            if (findResponse != null)
                if (findResponse.Endpoints != null)
                    if (findResponse.Endpoints.Count > 0)
                        var factory = new ChannelFactory<IStringService>(new BasicHttpBinding(),
                        var channel = factory.CreateChannel();
                Console.WriteLine("Could not find the Services");

Client uses the probe address that DiscoveryProxy provide to search for the services and also use the scope to narrow the search result. Once the client has found the specified Service endpoint it invokes 

Using the solutions 

There are three solutions

  • Rashim.RND.AdhocDiscovery 
  • Rashim.Discovery.Announcement.Solution
  • Rashim.RND.ManagedDiscovery

Rashim.RND.AdhocDiscovery is a sample app for ad-hoc discovery using the Simple Service Discovery. To see the output of the demo, first, you need to run Rashim.RND.AdhocDiscovery.ServiceHost and then need to run Rashim.RND.AdhocDiscovery.Client.

Rashim.Discovery.Announcement.Solution is also a demo app for ad-hoc discovery using the Announcement Service. For this solution, you need to run Rashim.Discovery.Announcement.Client and then need to run the Rashim.Discovery.Announcement.Server. Please note that, if you want to exit from the server or the client, you just press enter. For case of any ungraceful shutdown/exit of the server, the client might not get notification for the arrival and exit of the server.

Rashim.RND.ManagedDiscovery Solution is also another demo app for managed discovery using the DiscoveryProxy. To see the output, first you need to run the Rashim.RND.ManagedDiscovery.DiscoveryProxy, then need to run Rashim.RND.ManagedDiscovery.ServiceHost and finally also need to run Rashim.RND.ManagedDiscovery.Client. Please note that, you need to maintain the sequence of the project to run.


That's it 

That's it for now, I hope this article will help you to start working with WCF 4.0 discovery system.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Md. Rashim uddin
Software Developer (Senior) KAZ Software Limited.
Bangladesh Bangladesh
I am a true visionary as well as have always been passionate about learning. I always love to work with thought-provoking personnel to develop amazing, exciting and innovative ideas as part of an aggressive team that challenges my ingenious ideas, creativeness and extensive experience.

My Blog:

My Email: rashimiiuc at yahoo dot com

You may also be interested in...


Comments and Discussions

GeneralMy vote of 5 Pin
Amey K Bhatkar31-Aug-13 4:21
professionalAmey K Bhatkar31-Aug-13 4:21 
GeneralRe: My vote of 5 Pin
Md. Rashim uddin21-Sep-13 22:16
memberMd. Rashim uddin21-Sep-13 22:16 
QuestionMy vote of 5 Pin
Morshed Anwar3-Oct-12 23:20
memberMorshed Anwar3-Oct-12 23:20 
AnswerRe: My vote of 5 Pin
Md. Rashim uddin4-Oct-12 3:24
memberMd. Rashim uddin4-Oct-12 3:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170326.1 | Last Updated 4 Oct 2012
Article Copyright 2012 by Md. Rashim uddin
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid