One Two Three to Windows Communication Foundation: Part 2

In Part 1, we saw how to create a simple WCF service returning a string Hello World! In this part we will see how to consume the service in a rather simple console application.

Consuming the Service

We need a client to consume the service we created and display what the service returns. To create our client, we will add another project to our solution.

WCF1.jpg

Let's name the project "ConsoleHelloWorldServiceClient". The next step is to add the service reference to the client. That is, we let the client know where our service is hosted so that it can download the wsdl file. To do this, simply right-click on "References" in the client application, and choose "Service Reference".

WCF2.jpg

Click on "Discover" when the Service Reference dialog box opens, that will detect the service in the solution automatically.

WCF3.jpg

Name the service reference "HelloWorldServiceReference". That's it. We are done with the initial phase of consuming a WCF service. Next we need to code. We need to make a call to the function "SayHello()" of the service and wait until it completes its assigned operation, in this case returning a string. Here is the code of the Program.cs file of the ConsoleClientApplication.

using ConsoleHelloWorldServiceClient.HelloWorldServiceReference;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleHelloWorldServiceClient
{
    class Program
    {
        static  void Main(string[] args)
        {
            var client =
new HelloWorldServiceClient();           
            Console.WriteLine(client.SayHello());
            Console.ReadLine();         
         }    
     }
}

Just run the project and if your day is good, you must be greeted with the message, Hello World!

Now for the sake of description, we created an object named client of our service's client class. Next we make the call to the function SayHello() that will return a string, that we will display on the screen.

This article describes a simple WCF application. Next we will see the creatipn of some complex application and various service hosting techniques.

Happy Reading!!!


Similar Articles