How to host WCF service using Self Hosting
Create self hosting WCF service
In this article we will learn how to create self hosting WCF
service application. There are three difference hosting policy of WCF
- We can host in IIS
- Self hosting
- Host to Windows Active Server.
Now, among them the most popular hosting environment is on
IIS. More or less 70% of WCF application hosts on IIS server and near to 25 %
of application get host in same application domain which is nothing but self
When we will WCF self hosting then the service will run in
same application domain of main application. The advantage is that the calling
and accessing the service will be very quick and the main disadvantage of self
hosting is that ,if there is problem of application domain and if application
crashes then service will also stop.
Let’s create one simple WCF application to understand self
hosting practically. In this article we will get Name by ID from WCF service
Create one empty WCF template and modify default interface
public interface IInformationService
string GetName(int ID);
The interface is contains one method
which will return a string (name) according to its ID.
Now, we have to implement the interface in
concrete class. Here is implementation.
public class InformationService : IInformationService
List<string> Name = new List<string>();
public string GetName(int ID)
Within constructor we are creating few
random names and populating list. The GetName() method will take ID ad
parameter and it will return corresponding name from collection.
Now we have configured our WCF server and
we have to create client to consume the service. Let’s create one console
application and consume the WCF service. To consume the service we have to add
service reference in newly created console application. Go to Add service reference
option and click on it. We will find below dialogue box.
We have to press on Discover button to
discover the service automatically. Once we click on OK, the reference will be
added to the service.
Now, we can consume service from our
console application. Here is code to consume service.
static void Main(string args)
InformationServiceClient obj = new InformationServiceClient();
Console.WriteLine("Name is :- " + obj.GetName(1));
Here is sample output.
In this article we have seen how to
consume self hosted WCF service. Hope you have understood the concept. In coming article we will discuss more on same topic.