Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

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

4.72/5 (31 votes)
3 Feb 2011CPOL4 min read 204.5K   5.8K  
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.

Image 1

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.

Image 2

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.

Image 3

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.

C#
[ServiceContract]
public interface IService1
{
....
}

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

C#
[OperationContract]
string GetData(int value);

[DataMember] - defines the property exposed via service.

C#
[DataMember]
public bool BoolValue
{
  get { return boolValue; }
  set { boolValue = value; }
}

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

C#
[DataContract]
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:

XML
<system.serviceModel>
   <services>
     <service name="WcfServiceLibrary.Service1"
   behaviorConfiguration="WcfServiceLibrary.Service1Behavior">
       <host>
         <baseAddresses>
           <add baseAddress = "http://localhost:8080/Service1/" />
         </baseAddresses>
       </host>
       <!-- 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>
       <endpoint address ="" binding="wsHttpBinding"
       contract="WcfServiceLibrary.IService1">
         <!--
             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
             automatically.
         -->
         <identity>
           <dns value="localhost"/>
         </identity>
       </endpoint>
       <!-- 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"/>
     </service>
   </services>
   <behaviors>
     <serviceBehaviors>
       <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" />
       </behavior>
     </serviceBehaviors>
   </behaviors>
 </system.serviceModel>

Binding details: http://www.c-sharpcorner.com/UploadFile/pjthesedays/bindwcf05032009012251AM/bindwcf.aspx.

IService.Cs file

C#
namespace WcfServiceLibrary
{
    // NOTE: If you change the interface name "IService1" here, 
    // you must also update the reference to "IService1" in App.config.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);
 
 
        [OperationContract]
        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
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";
 
 
        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }
 
 
        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }
}

Service.cs

C#
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.

Image 4

Step 2

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

Image 5

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:

C#
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:

C#
host.Open();

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

Host.cs
C#
namespace HostApp
{
    class Program
    {
        static void Main(string[] args)
        {
            using (System.ServiceModel.ServiceHost host = 
		new System.ServiceModel.ServiceHost(typeof(Service1)))
            {
                host.Open();

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

                host.Close();
            }
        }
    }
}
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.
    XML
    <xmlns="http://www.w3.org/1999/xhtml"><xmlns="http://www.w3.org/1999/xhtml">
    <%@ 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.

Image 6

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:

C#
ServiceReference1.Service1Client client =  new Client.ServiceReference1.Service1Client();
Console.WriteLine(client.GetData(5));
Console.ReadLine();
client.Close();

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.

Summary

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

License

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