A Simple Example of WCF Service (Console Application)

This article discusses how to create a simple WCF service and how to call this service in our Client Console Application. In this example we will add three integers and the output will be shown in the Console Application.

Follow this simple procedure to create the service.

Step 1: First we will select "File" -> "New" -> "Web Site...". Then the following window will be shown:

WCF1.jpg

Here we select "WCF Service" and then type the name of the service (ExampleOfWCFService).

Step 2: There are two files in the App_Code Folder:

WCF2.jpg

Now we will write the code in the IService.cs page. Here we will create OperationContract like this:

[OperationContract]
int Add(int a, int b, int c);

Here we create an Operation Contract in which we declare the Add function and its three variables.

Step 3: Now we will write the code in the Service.cs Page:

public int Add(int a, int b, int c)

    {

        return a + b + c;

    }

Here we calculate the sum of the three variables and return it to the function.

Now run the program:

WCF3.jpg

Copy the address of the service; it is useful for finding the service in the client application.

Step 4: Now we will create a Console Application like this:

First we select "File" -> "New" -> "Project...". The Following window will be shown:

WCF4.jpg

Now we create a Console Application (MyConsoleApplication).

Step 5: Now we will add the Service Refrence of our WCF Service like this. We will right-click on our Console Application like this:

WCF5.jpg

WCF6.jpg

Here we will type or paste the address of our WCF Service and then click "Ok". Now we will write the following code, but first we will add the directive by right-clicking on the ServiceClient and then select the "Resolve" > "Using MyConsoleApplication.ServiceReference1" like this:

WCF7.jpg

After that the following directive will be added:

using MyConsoleApplication.ServiceReference1;

Now we will write the code:

ServiceReference1.ServiceClient myService = new ServiceClient();

            Console.WriteLine("Result:");

            int add = myService.Add(3, 21,27);

            Console.WriteLine(add);

            Console.ReadLine();

Here we use the addition "3+21+27" so the output will be: "51".

Output:

WCF8.jpg

 

Up Next
    Ebook Download
    View all
    Learn
    View all