Click here to Skip to main content
14,040,625 members
Click here to Skip to main content
Add your own
alternative version


92 bookmarked
Posted 24 Jan 2011
Licenced CPOL

Create, Host (Self Hosting, IIS hosting) and Consume WCF Service

, 3 Feb 2011
Rate this:
Please Sign up or sign in to vote.
Create, Host (Self Hosting, IIS hosting) and Consume WCF Service

What is WCF?

Windows Communication Foundation API allows to build distributed architecture in such manner that once created, service code can be utilized by the in-house application which using tcp/ip to communicate, web application using http protocol to communicate to web services, application using msmq. WCF Services also works with the application developed other than .NET Framework.

Create WCF Service

Follow the below listed step to create Service.

Step 1

Create service from Visual Studio. Select the go to C# or VB, then select project type WCF Service library or WCF service website project template.

The first one creates the *.dll and app.config file after the compilation which you can then use in your host application and expose the service to clients.

The second one creates the project with the proper web.config file and *.svc file which gets hosted on IIS via virtual directly and service gets exposed to client via HTTP protocol. So by that service cannot be exposed to Tclient. The benefit of this option is that there is no need to create host application you can directly host on IIS via virtual directory. For this discussion, first I am creating a WCF service library and then I am going to discuss about IIS deployment also.

Step 2

Create contract by specifying proper attributes. This contract tells the client what are the methods that get exposed by the service and custom type exposed by the service. You can decorate your contract by the list of attributes in System.ServiceModel namespace. You can create your own files or after selecting proper project type, it creates two files for your Iservice.cs and Service.cs. If you are going to create your own files, it's recommended that you can create your interface and implement it in your class.

[ServiceContract] - defines the interface to participate in provided service.

public interface IService1

[OperationContract] - defines the method going to be exposed by the service.

string GetData(int value);

[DataMember] - defines the property exposed via service.

public bool BoolValue
  get { return boolValue; }
  set { boolValue = value; }

[DataContract] - defines the custom data type exposed via service.

public class CompositeType

After you are done with the creation of the web service, your code should look as below.

Library app.config file

This file contains information about the metadata exchange defining endpoint of metadata. It also contains information about the endpoints where client talks with service. Endpoints are ABC means Address, Binding and Contract. As you see in the above config file service exposed for TCP communication by the following line:

     <service name="WcfServiceLibrary.Service1"
           <add baseAddress = "http://localhost:8080/Service1/" />
       <!-- Service Endpoints -->
       <!-- Unless fully qualified,
       address is relative to base address supplied above -->
       <endpoint address="net.tcp://localhost:9000/myservice"
       binding="netTcpBinding" contract="WcfServiceLibrary.IService1">

       <endpoint address ="" binding="wsHttpBinding"
             Upon deployment, the following identity element
        should be removed or replaced to reflect the
             identity under which the deployed service runs.
        If removed, WCF will infer an appropriate identity
           <dns value="localhost"/>
       <!-- Metadata Endpoints -->
       <!-- The Metadata Exchange endpoint is used by the service
   to describe itself to clients. -->
       <!-- This endpoint does not use a secure binding and
   should be secured or removed before deployment -->
       <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
       <behavior name="WcfServiceLibrary.Service1Behavior">
         <!-- To avoid disclosing metadata information,
         set the value below to false and remove the metadata endpoint
    above before deployment -->
         <serviceMetadata httpGetEnabled="True"/>
         <!-- To receive exception details in faults for debugging purposes,
         set the value below to true.  Set to false before deployment
         to avoid disclosing exception information -->
         <serviceDebug includeExceptionDetailInFaults="False" />

Binding details:

IService.Cs file

namespace WcfServiceLibrary
    // NOTE: If you change the interface name "IService1" here, 
    // you must also update the reference to "IService1" in App.config.
    public interface IService1
        string GetData(int value);
        CompositeType GetDataUsingDataContract(CompositeType composite);
        // TODO: Add your service operations here
    // Use a data contract as illustrated in the sample below to add 
    // composite types to service operations
    public class CompositeType
        bool boolValue = true;
        string stringValue = "Hello ";
        public bool BoolValue
            get { return boolValue; }
            set { boolValue = value; }
        public string StringValue
            get { return stringValue; }
            set { stringValue = value; }


namespace WcfServiceLibrary
    // NOTE: If you change the class name "Service1" here, 
    // you must also update the reference to "Service1" in App.config.
    public class Service1 : IService1
        public string GetData(int value)
            return string.Format("You entered: {0}", value);
        public CompositeType GetDataUsingDataContract(CompositeType composite)
            if (composite.BoolValue)
                composite.StringValue += "Suffix";
            return composite;

Hosting WCF Service

  • Self Host
  • IIS hosting
  • Windows service
  • WAS

Demo of Self hosting and IIS hosting.

Self Hosting

Step 1

Create new project >> Class Library >> name this project as Host.

Step 2

Add reference to the host application. Right click on Reference >> Add Reference.

Step 3

After adding reference to the host application to expose webservice for client to consume as you see below line of the code creates the object of the host and which is of type Service1 which we created in the WCF Service library project:

using (System.ServiceModel.ServiceHost host = 
	new System.ServiceModel.ServiceHost(typeof(Service1)))

As you can see, we used using block over so that it disposes host object when we close application.

Step 4

To start the service to handle request coming from the client of their service, you need to call open method:


and to stop receiving request, you need to call close method.

namespace HostApp
    class Program
        static void Main(string[] args)
            using (System.ServiceModel.ServiceHost host = 
		new System.ServiceModel.ServiceHost(typeof(Service1)))

                Console.WriteLine("Service started. press any key to stop it");

IIS Hosting
  1. To host same WCF library in your application, create WCF Web application project using WCF web application template as we discuss in start.
  2. Delete the files created in the IService.cs and Service.cs file from App_Code folder
  3. Include WCF library *.dll file which we created.
  4. Open Service.svc file and modify the single line in it.
    <%@ ServiceHost Language="C#" Debug="true" 
    Service="WcfServiceLibrary.Service1" %>

Change the web service WEB.Config file to expose service to client, i.e., you need to create same element as listed above in the app.config file of service library.

Consuming WCF Service

Step 1

Create new project >> Class Library >> name this project as Client as we created Host application. If you want to consume webservice hosted in your web application, start directly for the 2 step listed below.

Step 2

Add Service Reference to the client by Right clicking on project >> Add Service Reference.

which automatically creates the proxy files to consume web service, or make use of ServiceModel Metadata Utility Tool (Svcutil.exe), the command-line tool to generate proxy code from metadata.

svcutil /t:code http://<service_url> /out:<file_name>.cs /config:<file_name>.config   

Step 3

To send request to service from the client:

ServiceReference1.Service1Client client =  new Client.ServiceReference1.Service1Client();

So, as you see in the above code, you need to create object of Service1Client and then you can easily call the method exposed by the Service. If you want to see the auto-generated code, press F12 on the Service1Client which shows the proxy code to you.


As you follow the process listed step by step, it's quite easy to create, consume and host WCF Service.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Pranay Rana
Software Developer (Senior)
India India

Microsoft C# MVP (12-13)

Hey, I am Pranay Rana, working as a Team Leadin MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.

For me def. of programming is : Programming is something that you do once and that get used by multiple for many years

You can visit my blog

StackOverFlow -
My CV :-


You may also be interested in...


Comments and Discussions

QuestionReply Pin
Member 1052720430-Jul-15 1:56
memberMember 1052720430-Jul-15 1:56 
GeneralMy vote of 2 Pin
Member 923892320-Nov-14 21:02
memberMember 923892320-Nov-14 21:02 
SuggestionNot clear for complete starters like me. Pin
gopalakrishnach1-May-14 10:55
membergopalakrishnach1-May-14 10:55 
QuestionThanks . very Simple and Quick point to point Pin
ashu_om11-Mar-14 9:39
memberashu_om11-Mar-14 9:39 
QuestionIt's confusing the BaseAddress and the Endpoint Address - Pin
Dac10-Oct-13 11:28
memberDac10-Oct-13 11:28 
GeneralMy vote of 5 Pin
Sandesh M Patil16-Jul-13 6:14
memberSandesh M Patil16-Jul-13 6:14 
GeneralEasiest way to create and consume WCF Services in Pin
Lalit24rocks14-May-13 21:42
memberLalit24rocks14-May-13 21:42 
SuggestionNot Explained Properly Pin
Suprabhat Dutta25-Sep-12 6:34
memberSuprabhat Dutta25-Sep-12 6:34 
QuestionWCF Project Pin
chirag7mca22-Sep-12 0:48
memberchirag7mca22-Sep-12 0:48 
QuestionNot explain properly.. Pin
my_sanjeev18-Sep-12 0:49
membermy_sanjeev18-Sep-12 0:49 
GeneralMy vote of 1 Pin
sonu singh chauhan5-Sep-12 21:22
membersonu singh chauhan5-Sep-12 21:22 
GeneralMy vote of 5 Pin
Christian Amado24-Aug-12 5:44
professionalChristian Amado24-Aug-12 5:44 
GeneralMy vote of 5 Pin
sravani.v21-May-12 23:34
membersravani.v21-May-12 23:34 
QuestionConsume WCF service in Windows Service Pin
pankaj8813-May-12 18:40
memberpankaj8813-May-12 18:40 
GeneralMy vote of 5 Pin
Wilder Bellamy11-Apr-12 8:06
memberWilder Bellamy11-Apr-12 8:06 
QuestionWCF Service Application comes up under Visual C# but not VisualC#/Web on my box Pin
Wilder Bellamy10-Apr-12 9:40
memberWilder Bellamy10-Apr-12 9:40 
AnswerRe: WCF Service Application comes up under Visual C# but not VisualC#/Web on my box Pin
Wilder Bellamy11-Apr-12 4:44
memberWilder Bellamy11-Apr-12 4:44 
QuestionNeed Help Pin
vikram_sablok28-Mar-12 3:27
membervikram_sablok28-Mar-12 3:27 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey27-Mar-12 4:03
professionalManoj Kumar Choubey27-Mar-12 4:03 
GeneralMy vote of 5 Pin
Aditya Vikram Jaiswal3-Feb-11 20:16
memberAditya Vikram Jaiswal3-Feb-11 20:16 
GeneralMy vote of 5 Pin
Michael_Nattfalk27-Jan-11 22:51
memberMichael_Nattfalk27-Jan-11 22:51 
GeneralRe: My vote of 5 Pin
Pranay Rana27-Jan-11 22:53
professionalPranay Rana27-Jan-11 22:53 
GeneralMy vote of 5 Pin
kdgupta8725-Jan-11 0:29
memberkdgupta8725-Jan-11 0:29 
GeneralRe: My vote of 5 Pin
Pranay Rana25-Jan-11 0:33
professionalPranay Rana25-Jan-11 0:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.190425.1 | Last Updated 4 Feb 2011
Article Copyright 2011 by Pranay Rana
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid