For implementing the WCF discovery feature, the client needs to specify a criteria using which the service address can be looked up for communication. This is a mechanism of probing in which the client defines the criteria and looks for the endpoint. Generally client specifies the Contract for probing. When the client knows about the address of the WCF service, then a call to the service can be made, since the contract information is now available with the client. Let’s see some code.
Step 1: Open VS2010 and create a blank solution, name it as ‘WCF40_Runtime_Discovering_WCF_Services’. In this service, add a WCF Service application, name it as ‘WCF_SampleService’. Rename IService1.cs to IService.cs and Service1.Svc to Service.svc.
Step 2: Add a ServiceContract, OperationContract and DataContract in the IService.cs as below:
Step 3: Implement the IService service contract interface in the Service class as shown below:
Step 4: Write the following configuration in the web.config file. Add an endpoint with name udpDiscovery in the configuration. This endpoint is used to make the service discoverable. The UdpDiscoveyEndpoint class is used to make the service discoverable. This is a standard preconfigured endpoint for WCF Discoverable services.
Step 5: Publish the service on IIS.
Step 6: In the same solution, add a new WPF windows application, name it as ‘WPF40_DynamicClient’. In this client application, add the WCF Service reference. Name the namespace as ‘MyRef’.
Step 7: Open the app.config in the client application, and add the following endpoint in it.
<endpoint name="udpDiscoveryEndpoint" kind="udpDiscoveryEndpoint"/>
Step 8: In the MainPage.xaml, add a button and a DataGrid with AutoGeneratedColumns property set to ‘false’. Also define DataGridColumns as shown below:
Step 9: In the client project, add a reference to ‘System.ServiceModel.Discovery’. This is required to access the Probing classes. Also use this class in the MainWindow.Xaml.cs as below:
Step 10: In the button click event, now write the following code:
The above code makes use of the following classes:
In the above code, we read the address in the for-each loop, create a proxy object and then make a call to WCF service.
Step 11: Run the application and click on the ‘Get Employees’ button, the DataGrid will show all employees. You will find that the time to display data in the DataGrid is more because since this is probing, it may take time to complete the process for request and response.
Note: In a production scenario you can think of making an Async call to the WCF service so that the UI is not blocked till the call completes.
Download the source code
Will you give this article a +1 ? Thanks in advance