Host WCF In Console Application

In this article you will learn how to host WCF in Console Application.

In this article, we will learn how we can host a WCF service in a console application. The big advantage of doing this is that it is IIS independent and moreover, you do not need to add any .svc files. Just add simple interface and class files, with the service and operation contracts, and host it using the same console application.
 
So let's start by creating a new console application. Add an interface IMyService.cs and a class MyService.cs. Add a method named GetString in the interface, which accepts a parameter of type string and returns a string. Implement the interface in MyService class. So the code will look like the following:
  1. [ServiceContract]  
  2.  public interface IMyService  
  3.  {  
  4.      [OperationContract]  
  5.      String GetString(Int32 inputValue);  
  6.  }  
  7.   
  8.  public class MyService : IMyService  
  9.  {  
  10.      public string GetString(int inputValue)  
  11.      {  
  12.          return String.Format("Number generated is:{0}", inputValue);  
  13.      }  
  14.  }  
Next we need to create the service host, define endpoint and it's binding, based on the contract i.e. IMyService type and finally start the service by calling the Open(). So our code will look like the following: 
  1. class Program  
  2.    {  
  3.        static void Main(string[] args)  
  4.        {  
  5.            Uri _httpBaseAddress = new Uri("http://localhost:54663/MyService");  
  6.   
  7.            ServiceHost _svcHost = new ServiceHost(typeof(MyService), _httpBaseAddress);  
  8.   
  9.            _svcHost.AddServiceEndpoint(typeof(IMyService), new WSHttpBinding(), "");  
  10.   
  11.            ServiceMetadataBehavior serviceBehavior = new ServiceMetadataBehavior();  
  12.            serviceBehavior.HttpGetEnabled = true;  
  13.            _svcHost.Description.Behaviors.Add(serviceBehavior);  
  14.   
  15.            _svcHost.Open();  
  16.            Console.WriteLine("Service started at : {0}"_httpBaseAddress);  
  17.            Console.ReadKey();  
  18.        }  
  19.    }  
Now, simply run the application and you can see the service open.
 
 
Also you can browse the service by copying the url and pasting it in browser.
 

That's it, add the service reference by using the url above in your application and start calling the service. Happy coding..!!!
 
Read more articles on WCF: