19 Oct

Create, Host & Consume sample WCF service step by step

Share Button

In this tutorial, we are going to create a sample WCF project, host it on local and then create client application to consume the WCF. So, open your VS2010 solution and get set go with below steps.
Go to File->New->Project->WCFLibrary. Add a class file – Hello.cs.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Runtime.Serialization;

 

namespace HelloWCF

{

    [DataContract]

    public class Hello

    {

        [DataMember]

        public string name;

    }

}

Add a class file – IHelloService.cs. The best practice is to create an interface to define contracts. Contract specifies the structure of messages required to access operation offered by the service.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ServiceModel;

using System.Runtime.Serialization;

 

namespace HelloWCF

{

    [ServiceContract]

    public interface IHelloService

    {

         [OperationContract]

        string EnterName(string name);

    }

}

Add class HelloService.cs to implement the interface.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ServiceModel;

 

namespace HelloWCF

{

     [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]

    public class HelloService:IHelloService

    {

        public string EnterName(string name)

        {

            return “Hello world from “ + name + “!”;

        }

    }

}

Right click on App.config à Edit WCF configuration

On the services tab, select WCF service from bin.

image

Enter contract as IHelloService.

clip_image004

Press F5, you get to see the WCF Test Client. Copy the address and paste in browser.

clip_image006

clip_image008

Create a console application which will consume the WCF service.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using ClientApp.HelloServiceRef;

using System.Net;

namespace ClientApp

{

   class Program

    {

        static void Main(string[] args)

        {

            HelloServiceRef.HelloServiceClient ClientApp = new                HelloServiceClient();

            Console.WriteLine(ClientApp.EnterName(“GhostBuster”));

            Console.ReadLine();

        }

    }

}

Add service reference as below. Make sure the WCF is running on the localhost.

clip_image010

 

Now you are ready to run the program consuming WCF service.

Share Button