Home > Articles > WCF Articles > WCF Service Self Hosting

WCF Service Self Hosting

by Anand Kumar   on Oct 09, 2014   Category: WCF  | Level: Intermediate  |  Views: 2608    |  Points: 100   
Like this article? Bookmark and Share:
This article will describe what is self hosting and how to implement it.

 

Every WCF service needs to be hosted in a Windows Process called host process. WCF generally supports 4 types of hosting :

  1. Self Hosting

  2. IIS Hosting

  3. WAS (Windows Activation Services)

  4. Windows Service

In this article I am going to explain Self Hosting. First of all let me tell what is a Self Hosting Service :

“A service that runs with in an Application Process(Like Windows Application, Console Application) is called a Self Hosted Service. Lifetime of the service is controlled by Host Application. Host application sets the properties of the service, opens the service(which enables the service to listen the requests) and close the service.”

Now let me explain the stepwise implementation of self hosting.


Create Service Library :

It is best practice to create a service library and then use dll reference in host application.

So first let us create a Class Library Project named ServiceLibrary :

  1. Add reference to System.ServiceModel namespace.

  2. Now add using statement for System.ServiceModel to the class file.

  3. Define a new interface named IStringOperations and apply ServiceContractAttribute to the interface with a Namespace value of “http://Microsoft.ServiceModel.Samples/”. Specifying the namespace explicitly is a best practice because it prevents the default namespace value to be added to the contract name.

[ServiceContract(Namespace="http://WCFService.Samples")]
public interface IstringOperations

Declare methods in the interface that the IStringOperations contract will expose and apply OperationContractAttribute to each method that you want to expose as part of the wcf public contract.

[OperationContract]
int StringLength(string str);
[OperationContract]
string ConcatenateStrings(string str1, string str2);

Now service interface contract is created, so we will proceed to implementation of the interface contract.

    Now create a class named StringOperations that implements IstringOperations interface :

public class StringOperations : IStringOperations
  1. Now we will implement each method in StringOperations class that is declared in IStringOperations interface.

public class StringOperations : IStringOperations
public int StringLength(string str)
{
        return str.Length;
}
public string ConcatenateStrings(string str1, string str2)
{
return str1 + str2;
}

  7. Service contract and its implementation are done, our final code for the file looks like :

using System;
using System.ServiceModel;
namespace ServiceLibrary
{
//Define a service contract
[ServiceContract(Namespace="http://WCFService.Samples")]
public interface IStringOperations
{
//Method declaration for contract
[OperationContract]
int StringLength(string str);
[OperationContract]
string ConcatenateStrings(string str1, string str2);
}
public class StringOperations : IStringOperations
{
public int StringLength(string str)
{
return str.Length;
}
public string ConcatenateStrings(string str1, string str2)
{
return str1 + str2;
}
}
}

Now build the project.



Create Host Application :

Now we are already done with service contract and its implementation. Our next step is to create a host application that will host the service.

  1. Create a Wondows Console application named ServiceHostApp.

  2. Now add reference to the ServiceLibrary.dll, that will be available in bin folder of ServiceLibrary project that we have created and build previously, and add using statement for the ServiceLibrary namespace.

using ServiceLibrary;
  1. Add reference to System.ServiceModel namespace.

  2. Now we need to create a Uri instance for the base address of service :

Uri baseAddress = new Uri("http://localhost:8000/ServiceSample/Service");
  1. Create a new ServiceHost instance to host the service. It requires the type that implements service contract and the base address as arguments :

ServiceHost selfHost = new ServiceHost(typeof(StringOperations), baseAddress);
  1. Add try catch block to abort the service if error occurs.

  2. Now add an endpoint to expose the service. To add an endpoint it needs contract, binding and address for endpoint. Here contract is IStringOperations, binding can be used according to requirement let us use WSHttpBinding, as an address it requires relative address of the service that is “StringOperations”. So the full address of the service is :

http://localhost:8000/ServiceSample/Service/StringOperations
selfHost.AddServiceEndpoint(typeof(IStringOperations), new WSHttpBinding(), "StringOperations");

Add using statement for System.ServiceModel.Description namespace

using System.ServiceModel.Description;
  1. Now enable metadata exchange. To do this first create MetadataBehavior object and set HttpGetEnabled to true and then add this Service Behavior to service host.

ServiceMetadataBehavior metaData = new ServiceMetadataBehavior();
metaData.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(metaData);
  1. Now we need to open the service host so that it can listen to the incoming requests and when user presses the enter key close the service host.

selfHost.Open();
Console.WriteLine("Service the ready to process the request");
Console.WriteLine("Press Enter key to terminate the service");
Console.ReadLine();
selfHost.Close();

  11. Now self hosting for service is done, one important point is that such services require admin permission to register http addresses on machine for listening. So our host application should run with administrator permission. Means run the VS with Run as Administrator and then run the host application. To check the service is running or not open the below link in browser :

http://localhost:8000/ServiceSample/Service

Now our host application is done, the complete code for Program.cs looks like :

using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using ServiceLibrary;
namespace SeviceHostApp
{
class Program
{
static void Main(string[] args)
{
//Service base url
Uri baseAddress = new Uri("http://localhost:8000/ServiceSample/Service");
ServiceHost selfHost = new ServiceHost(typeof(StringOperations), baseAddress);
try
{
//Add end point
selfHost.AddServiceEndpoint(typeof(IStringOperations), new WSHttpBinding(), "StringOperations");
ServiceMetadataBehavior metaData = new ServiceMetadataBehavior();
metaData.HttpGetEnabled = true;
//Add metadata to service host
selfHost.Description.Behaviors.Add(metaData);
//Start the service
selfHost.Open();
Console.WriteLine("Service the ready to process the request");
Console.WriteLine("Press Enter key to terminate the service");
Console.ReadLine();
//Shut down the service
selfHost.Close();
}
catch (CommunicationException ex)
{
Console.WriteLine("Exception occured : {0}", ex.Message);
selfHost.Abort();
}
}
}
}

Now our final step is to create a Client application that will consume the service.

Create Client Application :

  1. Create a console application named “ServiceClient”.

  2. Add reference to System.ServiceModel.dll and add a using statement for System.ServiceModel namespace.

using System.ServiceModel;
  1. Now run the service host and add reference to the service in client application. We can directly add service reference to the client application via right clicking the .csproj and click on “Add Service Reference” option and use the service address to add reference :

http://localhost:8000/ServiceSample/Service

and name the namespace as “ServiceProxy”.

Or we can use Service Model Metadata Utility Tool (SvcUtil.exe) on VS command prompt to generate the service proxy and config file as :

svcutil.exe /language:cs /out:ServiceProxy.cs /config:app.config http://localhost:8000/ServiceSample/Service

and put these to generated files in root folder in client application and include them to the project.

  1. Now add using statement for ServiceClient.ServiceProxy namespace :

using ServiceClient.ServiceProxy;
  1. Create service client object :

StringOperationsClient client = new StringOperationsClient();
  1. Now call the service operations from with in the client.

using System.ServiceModel;
var str1 = "India";
var str2 = " is great.";
var str1Length = client.StringLength(str1);
Console.WriteLine("Length ({0}) : {1}", str1, str1Length);
var strConcate = client.ConcatenateStrings(str1, str2);
Console.WriteLine("Concate ({0},{1}) : {2}", str1, str2, strConcate);

Complete code for Program.cs for Client looks like :

using System;
using System.ServiceModel;
using ServiceClient.ServiceProxy;
namespace ServiceClient
{
class Program
{
static void Main(string[] args)
{
StringOperationsClient client = new StringOperationsClient();
var str1 = "India";
var str2 = " is great.";
var str1Length = client.StringLength(str1);
Console.WriteLine("Length ({0}) : {1}", str1, str1Length);
var strConcate = client.ConcatenateStrings(str1, str2);
Console.WriteLine("Concate ({0},{1}) : {2}", str1, str2, strConcate);
Console.WriteLine("Please press <Enter> to terminate.");
Console.ReadLine();
}
}
}

Now run the client application and enjoy self hosting, it will give output as :

Length (India) : 5

Concate (India, is greate.) : India is great.

Please press<Enter> to terminate.

Hope it will help to understand and implement self hosting.

 



Like this article? Bookmark and Share:

Most viewed Articles

User Comments


  Re :WCF Service Self Hosting   
Posted by Thamil
on 10/9/2014 2:31:31 AM
Points : 10

Hi Anand Kumar,

Great, Thanks for sharing this article.

Submit feedback about this article

Please sign in to post feedback

Latest Posts