Dot Net For All

Adding WCF Service reference to Client

In this article I will show how to add a WCF service reference to the client and what role does service metadata exchange plays. As I discussed in one of my previous article how to create and host the WCF service in C#. In that article I have created the service without using the WCF service template provided by the visual studio.

In the same article I have created the client proxy using ClientBase class.

In this article I will show how to add the service reference to the client using visual studio. To add the service reference using visual studio the most important thing we should know about the metadata exchange and how to enable it.

What is Metadata?

Metadata Exposure

As shown in the below figure we have to add the host section. Host section is used to provide a base address where we find the service metadata. The other section which we need to add is the behaviours section in the app.config of the host. The example for both of these is shown in the below figure.

In place of localhost you can provide the IP address of the machine where you want to host the service. I have used localhost as I will be accessing the service from local machine along with the port.

Adding Metadata exchange support to WCF service

Adding WCF Service Reference to the Client

To add the WCF service reference to the client right click on the references. Click on Add service reference. We will get a window as shown in the figure below.

As you can see in the above figure I have added the base address of the service. Click on the “Go” button. You can see the service is added under services box. Add a service namespace. I have named it as HelloWorldServiceNew.

We can access the service operations on client side as shown in the code below.

HelloWorldServiceNew.PersonData data = new HelloWorldServiceNew.PersonData() { FirstName = "Vikram" };
HelloWorldServiceNew.MyServiceClient client = new HelloWorldServiceNew.MyServiceClient();
Console.WriteLine(client.Hello(data));

Conclusion:

In this article I have shown you how to add the service reference using Visual studio. I have also discussed about the metadata exchange and its importance in WCF service.

I have used the service project code from here.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview