Click here to Skip to main content
15,868,292 members
Articles / Web Development / ASP.NET

A Beginner's Tutorial on How to Host a WCF Service (IIS Hosting and Self Hosting)

Rate me:
Please Sign up or sign in to vote.
4.78/5 (75 votes)
22 Feb 2013CPOL11 min read 509.9K   12K   129   34
In this article we will see how we can host a WCF service(IIS Hosting and Self Hosting).

Introduction

In this article we will see how we can host a WCF service. We will look at various ways a WCF service can be hosted and what are the benefits and drawbacks of each hosting method. We will also create a sample client application that will consume the WCF service hosted in different ways.

Background

This article assumes that reader has some basic knowledge of WCF services. Please refer to the following article to get a refresher on WCF in case it is needed: A Beginner's Tutorial for Understanding Windows Communication Foundation (WCF)

In a service oriented architecture the standalone service is of no use unless it is exposed to the client. To expose a service to the client it needs to be hosted somewhere. By hosting we not only mean a server for hosting but also the application that will host the service as a part of itself.

Traditional web services were hosted on IIS. This approach has a lot of benefits which includes not worrying about the creation and disposal of service, On demand availability of web services etc. But this approach has one major drawback i.e. protocols other than HTTP are not supported.

WCF comes with the possibility of being invoked and used by protocols other than HTTP. So along with IIS, WCF can also be hosted in different ways so that its full power can be utilized(if required).

A WCF service can be hosted in following ways:

  1. Hosting in Internet Information Services(IIS).
  2. Hosting in Windows Activation Services(WAS).
  3. Hosting in a Console or Desktop application(Self hosting).
  4. Hosting in a Windows Service.

Every method of hosting comes with its own benefits and drawbacks. Let us see each the theory behind each hosting method one by one.

Hosting a WCF service in IIS is perhaps the easiest method. It is straight forward process for the developers who are familiar with ASP.NET websites and ASMX web services because the WCF service is also hosted in IIS in similar manner. Also, IIS takes care of creation of service instances, disposal of service instances, recycling and other activities that it does for ASP.NET website. It treats a WCF service like an ASP.NET website and provides all the features of having multiple request handling and dynamic compilation to a WCF service out of the box.

if we are using IIS6 or previous version then the major drawback of IIS6.0 hosting is that only HTTP/HTTPS protocol can be used to communicate with the service. Which actually is sufficient for most of the project but if the project needs to communicate to the service using other protocols then this IIS6.0 hosting will not suffice.

Now the point to notice in the above text is that I specifically mentioned IIS 6.0 or previous. The reason for this is that IIS 7.0 comes with a feature/component called Windows Activation Service(WAS). So hosting a WCF service in WAS and IIS 7.0 are actually not exclusive. TO host a WCF service using WAS, we need to still host the service in IIS 7.0 and then enable the support for protocols other than HTTP/HTTPS. Hosting in WAS comes with all the benefits of hosting in IIS and on top of that it supports all the protocols too.

Now the next process of hosting i.e. self hosting has the major benefits of providing us full control i.e. All the control of starting the service, stopping the service and error handling/logging can be done in our host application. The amount of code that needs to be written to self host a WCF service is very small and it is very easy too. Now the decision for chooing self hosting is purely on the requirements of whether or not you want so much control on the service.

Finally, Hosting the service in a windows service is same as self hosting but the service creation and disposing will be abstracted in form of a Windows service. It provides the same capabilities as a self hosted service provides and the decision of whether to use this method or not will rely on the same factors of whether or not you want so much control on the service.

Using the code

Now that we know the various methods of hosting a WCF service, we can say that if we know how to host a WCF service in IIS, we can make some changes on top of that and host it in WAS too. Similarly, If we understand how to self host a service, we can create a windows service host with the same process.

Now in the rest of the article, our focus will be to create a sample service and see how we can host it in IIS and how we can self host it. Then we will touch upon the steps that are needed to host the service on WAS and inside a windows service.

Note: Only IIS hosting and self hosting are discussed in detail in rest of the article because these are the most commonly used methods of hosting and other hosting process will be similar but they have some additional steps.

Creating the Service Library

We can always keep the service code in the host application (in case of self hosting) or inside an ASP.NET website(IIS hosting) but it is always a good idea to have the WCF service in a class library. That way we decouple the service implementation from its host application. Also, we can have a single WCF service and multiple host applications hosting that service.

Let us create a simple WCF service library that will take the users name in form of a DataContract and then return him a greeting message from the service. Let us start by creating a simple WCF Service library.

Image 1

In this service we create a simple DataContract called Person which will keep the user Name.

C#
[DataContract]
public class Person
{
    [DataMember]
    public string Name { get; set; }
}

Now we will have a very simple single method ServiceContract that will take the Person and return a string with containing the greeting message.

C#
[ServiceContract]
public interface ISampleService
{
    [OperationContract]
    string GreetMe(Person person);
}

Finally, we will create the class that will implement the service contract.

C#
public class SampleService : ISampleService
{
    public string GreetMe(Person person)
    {
        return string.Format("Greetings from Sample service Mr. {0}", person.Name);
    }
}

Now we have a very simple toy service ready to play with. To check the working of the service we can simply run the WCF service library project. By doing this a WCF Test Client will open up using which we can test the working of our service. This tool can be used to test the calls to the service and response from the service.

Image 2

Now one question we should ask is how this service started running without configuring any endpoints. Actually when we create a WCF service library some default configuration with endpoints, address and

Bindings
get created in the library's App.config file.

XML
<service name="SampleServiceNamespace.SampleService">
    <endpoint address="" binding="wsHttpBinding" contract="SampleServiceNamespace.ISampleService"> 
</endpoint>

Now this configuration will be used when we try to run a service library and Visual studio will take care of hosting this service for us for testing purpose. The important point here is that when we host this service ourselves then this App.config configuration will be of no use. The host application will have to define its own endpoints and specify the Address, Binding and Contracts separately. 

Note: The configuration section shown above is not complete. Please refer to the sample code to see the complete App.config file.

Hosting the Service in IIS

Now that we have our service ready with us let us go and see how we can host this service in IIS. For this let us go and create a new website specifically WCF Service website.

Image 3

Now this website comes with its own predefined service template but we are not going to use them so we will delete all of them and then add a reference to our service library project in this website.

Once we have the reference to our service library added, its time to create a service and configure endpoints with required address, binding and contracts. Since we will host this website in the IIS, the address of the .SVC file will become the address of the Service. Now the binding used by default when we try to host a service in IIS is basicHttpBinding. And for the contract part, we need to specify the contract that should be used from our service library. This can be done by changing the SVC file and pointing the SVC file to the right service implementation.

XML
<%@ ServiceHost Language="C#" Debug="true" Service="SampleServiceNamespace.SampleService"%>

And this will suffice for the service to run within IIS. If we configure this website in IIS and run the .svc file the service will start running hosted in the IIS. 

Image 4

Now we have a service hosted on IIS and it is running. We will see how we can consume this IIS hosted service later in this article.

Self Hosting the Service

To self host the service let us create a simple Console application that will host the service, open the service and close the service. Let us start by having a simple console application.

Once the console application is created, let us add the reference to the Service library into this application. Along with the reference of service library, we also have to add reference to System.ServiceModal and System.Runtime.Serialization in this project to get it to work with WCF hosting process.

Now we have the service library added in this project along with all other required references. Now we have to define the endpoints, address, binding and contracts for this service. This can be done either declarative (via configuration file) or imperatively(via code). Let us do it declarative by having the service configured in the app.config file.

XML
<services>
    <service name="SampleServiceNamespace.SampleService">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration=""
            contract="SampleServiceNamespace.ISampleService" />       
        <host>
            <baseAddresses>
                <add baseAddress="http://localhost/SelfHostedServiceConsole" />
            </baseAddresses>
        </host>
    </service>
</services>

We configured this service to use HTTP protocol with basicHttpBinding. The address of the service is http://localhost/SelfHostedServiceConsole and the contract is specified as the service contract from our service library i.e. SampleServiceNamespace.ISampleService

Note: I really recommend using the "Edit WCF Configuration Tool" that comes with Visual studio(right click the app.config file). This really makes the declarative configuration of WCF service very easy.

Now that we have specified the ABC of this service and exposed an endpoint, its time to see how we can host the service. To host the service and open the service host we need to use the ServiceHost class. below code shows how the service can be hosted using the endpoints defined in the above config file.

C#
using (ServiceHost host = new ServiceHost(typeof(SampleServiceNamespace.SampleService)))
{
    host.Open();

    Console.WriteLine("Service up and running at:");
    foreach (var ea in host.Description.Endpoints)
    {
        Console.WriteLine(ea.Address);
    }

    Console.ReadLine();
    host.Close();
}

And when we run the host:

Image 5

To check the self hosted service, Let us start the host and then type the address in the browser.

Image 6

And this confirms that the service has been hosted successfully.

Consuming the WCF service

Let us now go ahead and create a simple Console application to test these two services. First let us create a simple console application. Once we have the console application created, let us add two service reference to it. One for the IIS hosted service and other for the self hosted service.

Note: To add the IIS hosted service reference, use the address of the .svc file and to add the reference of self hosted service, use the address specified in the config file of self hosting console. Also, make sure that the hosting console application is running while adding the service reference.

Image 7

Once we add the service reference the client side endpoints have already been configured in the app.config file. For now we will use this configurations only. Adding the service reference also created the proxy classes for the service. So let us see how we can use these proxy classes to call our IIS hosted and Self hosted WCF service.

C#
static void Main(string[] args)
{
    // Using the IIS hosted service
    Console.WriteLine("Using the IIS hosted service");
    using (IISHostedService.SampleServiceClient client = new IISHostedService.SampleServiceClient())
    {
        IISHostedService.Person p = new IISHostedService.Person { Name = "Rahul" };
        Console.WriteLine(client.GreetMe(p));
    }

    Console.WriteLine();

    // Using the Self hosted service
    Console.WriteLine("Using the Self hosted service");
    using (SelfHostedService.SampleServiceClient client = new SelfHostedService.SampleServiceClient())
    {
        SelfHostedService.Person p = new SelfHostedService.Person { Name = "Rahul" };
        Console.WriteLine(client.GreetMe(p));
    }

    Console.ReadLine();
}

And when we run the application

Image 8

And this shows us that both our IIS hosted and self hosted services are running.

Point of interest

In this article, we started our discussion with the various possible ways of hosting a WCF service. We saw how to host a service in IIS and how to self host a service. We have not touched the WAS hosting and Hosting inside a Windows service but these processes will require something additional to be done on top of IIS hosting and self hosting respectively. Since WAS and Windows service knowledge will automatically let the user know how and what additional needs to be done, I skipped these two methods from this article(otherwise the article would have become digressing).

Also, I used basic HTTP binding and default behaviors for all demos because the intention of the article was to talk about hosting the WCF service. But these things can easily be tweaked in the hosts and clients (proved they conform to hosting environments capabilities). This article was written from a perspective of beginner's in WCF. I hope this has been informative. 

History

  • 22 February 2013: First version.

License

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


Written By
Architect
India India

I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.

  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]

  • Microsoft MVP 2015

Comments and Discussions

 
QuestionExactly what I was looking for Pin
pollilfax29-Aug-19 3:57
pollilfax29-Aug-19 3:57 
QuestionWCF and SOAP Pin
Sharath Somanathan4-Apr-18 9:32
Sharath Somanathan4-Apr-18 9:32 
Suggestion[My vote of 2] Not enough Pin
kailas8328-Nov-17 0:45
kailas8328-Nov-17 0:45 
GeneralRe: [My vote of 2] Not enough Pin
Junior Coder8-Feb-18 22:33
Junior Coder8-Feb-18 22:33 
Questionnot detailed enough Pin
Member 1323178830-May-17 13:30
Member 1323178830-May-17 13:30 
QuestionOnce hosted in IIS web config does not have endpoints from app config? Pin
Member 98828491-Feb-17 12:50
Member 98828491-Feb-17 12:50 
QuestionNice Article - I would like to address a few gotchas to help other WCF Service beginners. Pin
frontier_teg15-Apr-15 6:35
frontier_teg15-Apr-15 6:35 
QuestionAdding service reference is disabled if we run the console application. So, how to add service reference? Pin
Member 1137148825-Jan-15 2:24
Member 1137148825-Jan-15 2:24 
QuestionSimple wcf demo Pin
Ankush_B5-Dec-14 2:22
Ankush_B5-Dec-14 2:22 
AnswerRe: Simple wcf demo Pin
Rahul Rajat Singh5-Dec-14 3:02
professionalRahul Rajat Singh5-Dec-14 3:02 
GeneralAwesome Pin
Yamin Khakhu12-Sep-14 17:00
professionalYamin Khakhu12-Sep-14 17:00 
GeneralGood article Pin
phyrex13-Aug-14 23:40
phyrex13-Aug-14 23:40 
QuestionIIS Hosting. Which IIS? Pin
yuriygo3-Aug-14 15:00
yuriygo3-Aug-14 15:00 
When you are talking about IIS hosting, what web server do you mean: the Visual Studio built-in web server, or the IIS on the local machine?
Because you do not mention anything regarding the local IIS website configuration I think the VS built-in webserver is used. Is it corerct?
QuestionNeed more details Pin
yuriygo3-Aug-14 14:00
yuriygo3-Aug-14 14:00 
QuestionHosting the Service in IIS Pin
Alexandros Pappas25-Jul-14 2:09
professionalAlexandros Pappas25-Jul-14 2:09 
SuggestionRe: Hosting the Service in IIS Pin
tjfan5-Aug-15 15:15
tjfan5-Aug-15 15:15 
QuestionWCF Service v WCF Web App? Pin
Miles Gibson8-May-14 10:17
Miles Gibson8-May-14 10:17 
QuestionConsuming wcf service from hosting website Pin
Member 1041391917-Apr-14 12:19
Member 1041391917-Apr-14 12:19 
QuestionThanks a lot for posting example in simple way. Pin
Member 1053105025-Feb-14 23:49
Member 1053105025-Feb-14 23:49 
GeneralNice article Pin
Prasannala3-Dec-13 19:12
Prasannala3-Dec-13 19:12 
QuestionMany Thanks. Pin
jeffreymen3-Dec-13 11:35
jeffreymen3-Dec-13 11:35 
GeneralThis was very helpful Pin
TomP6918-Nov-13 9:48
TomP6918-Nov-13 9:48 
QuestionWCF Service Application deployment Pin
Ganesh Satpute31-Oct-13 22:22
Ganesh Satpute31-Oct-13 22:22 
GeneralNice Pin
Bhuvanesh Mohankumar29-Oct-13 18:45
Bhuvanesh Mohankumar29-Oct-13 18:45 
QuestionClient from another Computer in the network Pin
XcyTheR28-Oct-13 6:02
XcyTheR28-Oct-13 6:02 

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.