WCF Hosting in Windows Service Simplified

By | June 2, 2014

We have discussed briefly about different available hosting options (Self Hosting, Windows Service, IIS, WAS etc) for WCF Service in separate post “WCF Interview Questions and Answers – Part 1“. In this WCF Tutorial, we are going to implement hosting WCF Service in a Windows Service. Hosting in Windows Service is suitable for long-running WCF Service where the lifetime of the service is controlled by operating system.

Remember, in previous WCF Tutorial, we have already implemented WCF Self Hosting in a Console Application with example using a step by step approach. In this WCF Service Tutorial, we will follow the same step by step approach to host WCF Service as:

  • Creating a Class Library for WCF Service
  • Adding a Windows Service

Create a Class Library i.e. StudentService:

In Visual Studio, create a new Class Library Project, name it as “StudentService” and press “OK” button.

WCF Self Hosting

Then, right click on project and Add a new “WCF Service” to this Class Library Project.

WCF Self Hosting

It will add Service Contract (IStudentService) and it’s implementation class (StudentService) to class library project. Also, it will add a reference to System.ServiceModel.
Code for IStudentService interface will be as follows:
 [ServiceContract] public interface IStudentService 
 {
     [OperationContract]
     string GetStudentInfo(int studentId); 
 }
And following is the code for StudentService implementation class:
      public class StudentService : IStudentService
     {
         public string GetStudentInfo(int studentId)
         {
             string studentName = string.Empty;
             switch (studentId)
             {
                 case 1:
                     {
                         studentName = “Muhammad Ahmad”;
                         break;
                     }
                 case 2:
                     {
                         studentName = “Muhammad Hamza”;
                         break;
                     }
                 default:
                     {
                         studentName = “No student found”;
                         break;
                     }
             }
             return studentName;
         }
     }
Now, we are done with our WCF Service i.e. StudentService. For the purpose of simplicity, we are going to add Windows Service project to same solution.
Adding a Windows Service:
In order to host this WCF Service in Windows Service, let’s add a new Windows Service project “WinServiceStudentHost” to this solution.

Windows Service

Our Windows Service will have reference to:
  • StudentService class library
  • System.ServiceModel.

WCF Service Reference

System.ServiceModel
As we want to host our WCF Service when Windows Service get started. We will write WCF Service hosting code in OnStart() method of Windows Service (StudentHost.cs) and close the Service Host in OnStop() method accordingly.

namespace WinServiceStudentHost
{
    public partial class StudentHost : ServiceBase
    {
          ServiceHost studentServiceHost = null;
                       
          public StudentHost()
         {
                  InitializeComponent();
         }
         protected override void OnStart(string[] args)
        {
             try
            {
                    //Base Address for StudentService
                   Uri httpBaseAddress = new Uri(“http://localhost:4321/StudentService”);
                   studentServiceHost = new ServiceHost(typeof(StudentService.StudentService),httpBaseAddress);
                   //Add Endpoint to Host
                   studentServiceHost.AddServiceEndpoint(typeof(StudentService.IStudentService),
                                                                                                                                    new WSHttpBinding(), “”);
                   //Metadata Exchange
                   ServiceMetadataBehavior serviceBehavior = new ServiceMetadataBehavior();
                   serviceBehavior.HttpGetEnabled = true;
                   studentServiceHost.Description.Behaviors.Add(serviceBehavior);
                    //Open
                    studentServiceHost.Open();
            }
            catch (Exception ex)
            {
                   studentServiceHost = null;
            }
       }
       protected override void OnStop()
       {
             if (studentServiceHost != null)
             {
                studentServiceHost.Close();
                studentServiceHost = null;
              }
       }
   }
}

Note: Dont’ forget using System.ServiceModel and System.ServiceModel.Description.

Also, code for Main() method in Program.cs will be as follows:

namespace WinServiceStudentHost
{
        static class Program
        {            static void Main()
            {
                 ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                         new StudentHost()
                };
               ServiceBase.Run(ServicesToRun);
            }
         }
}

For our Windows Service to be installed, we need to add an installer class to our project. Right click on Windows Service project i.e. WinServiceStudentHost and choose Add->New Item -> Installer Class as follows:

WCF Host Installer

Following is the code for Host Installer class:

namespace WinServiceStudentHost
{
     [RunInstaller(true)]
     public partial class StudentHostInstaller : System.Configuration.Install.Installer
     {
            public StudentHostInstaller()
           {//Process
              ServiceProcessInstaller process = new ServiceProcessInstaller();
              process.Account = ServiceAccount.NetworkService;              //Process
              ServiceInstaller service = new ServiceInstaller();              service.ServiceName = “StudentHostWindowService”;
              service.DisplayName = “StudentHostWindowService”;
              service.Description = “Student WCF Service Hosted Successfully.”;
service.StartType = ServiceStartMode.Automatic;

              Installers.Add(process);
              Installers.Add(service);
           }
      }
}

Note: Don’t forget using System.ServiceProcess.

Finally, we need to build our project. We can install our Windows Service through Visual Studio Command Prompt using InstallUtil utility. We will point to WinServiceStudentHost.exe in InstallUtil command  as shown in below diagram.

InstallUtil

Our Windows Service is installed successfully and hosted our StudentService. Now, we can easily consume that WCF Service in a Client Application. For implementation on creating a proxy to consume a WCF Service, you can follow my previous WCF Tutorial on Calling a WCF Self Hosting Service.

Hopefully, this WCF Service Tutorial will help in practically implementing Hosting WCF Service in Windows Service.
Other Related Tutorials:

Top 10 Interview Questions and Answers Series:

Category: Uncategorized Tags: ,

About IMRAN ABDUL GHANI

Imran Abdul Ghani is working as Software Developer(Senior) with extensive knowledge in Web development technologies especially C#, ASP.NET, MVC, WCF, Web API, ADO.NET Entity Framework, jQuery etc. He has several years of experience in designing/developing enterprise level applications. He is Microsoft Certified Solution Developer for .NET (MCSD.NET) since 2005. You can reach his blogging at www.webdevelopmenthelp.net, www.topwcftutorials.net, and www.sharepointfordummies.net.