In part 1, we have seen 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 service returns. To create our client, we will add another project in our solution.
Let’s name the project as ConsoleHelloWorldServiceClient. Next step would be adding 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 from. To do this, simply right click on References in the client application, and choose service reference.
Click on discover when the service reference dialog box opens, which will detect the service in the solution automatically.
Name the service reference as HelloWorldServiceReference. That’s it. We are done with 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.
1: using ConsoleHelloWorldServiceClient.HelloWorldServiceReference;
2: using System;
3: using System.Collections.Generic;
4: using System.Linq;
5: using System.Text;
6: using System.Threading.Tasks;
7:
8: namespace ConsoleHelloWorldServiceClient
9: {
10: class Program
11: {
12: static void Main(string[] args)
13: {
14: var client = new HelloWorldServiceClient();
15: Console.WriteLine(client.SayHello());
16: Console.ReadLine();
17: }
18: }
19: }
Just run the project and if your day is good, you must be greeted with a 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, which we will display on the screen.
This is a simple WCF application describing post. Next we will see creating some complex application and different service hosting techniques.
Happy Reading!!!
0 comments