Consuming WCF Service

The purpose of this tutorial is to show you how to make a call to a WCF Service in the context of a WPF application. The following common tasks will be examined:

  • Adding a reference.

  • Creating a new instance of the service.

  • Making call to the service.

The process of developing a WCF Service is beyond the scope of this tutorial. For more information read here.

This tutorial will use the Northwind database, which can be downloaded from here.

For the purpose of this tutorial will be used a service that exposes the following method:

  • LoadCategories - load all categories from the Categories table in the Northwind database.

Adding Reference

The first step is to add a new service reference to your application. In order to do that you need to perform the following steps:

  • Select the "References" folder, right click with your mouse button and choose "Add Service Reference..." Common Consuming Data Wcf Service 010

  • A popup window appears; hit the Discover button to find the web service or enter the service location. Press OK to add it. Common Consuming Data Wcf Service 020

You have the ability to choose the type of the collections that the service returns. In order to do that you need to open the Service Reference Settings dialog from the Advanced button. Common Consuming Data Wcf Service 030

When a service reference is added to a project, any types defined in the service are generated in the local project. In many cases, this creates duplicate types when a service uses common .NET Framework types or when types are defined in a shared library. To avoid this problem, types in referenced assemblies are shared by default. If you want to disable type sharing for one or more assemblies, you can do so in the Service Reference Settings dialog.

Once the WCF service is added all needed assemblies and configuration files will be automatically included in your project.

Creating New Instance of the Service

Creating new instance of the service is a pretty simple process.

WcfService.SampleWcfServiceClient serviceClient = new WcfService.SampleWcfServiceClient(); 
Dim serviceClient As New WcfService.SampleWcfServiceClient() 

Don't forget to give a meaningful name for your WCF Service namespace. In the previous example the namespace is "WcfService".

Making Asynchronous Call to the Service

In order to make a call to your service, you just need to invoke the exposed by the service method:

foreach( Categories c in serviceClient.LoadCategories() ) 
    this.Categories.Add( c ); 
For Each c As Categories In serviceClient.LoadCategories() 

See Also

In this article
Not finding the help you need? Improve this article