Click here to Skip to main content
12,695,404 members (28,860 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

3.7K views
5 bookmarked
Posted

WCF Hosting in Windows Service Simplified

, 16 Jun 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
WCF Hosting in Windows Service simplified

We have discussed briefly about different available hosting options (Self Hosting, Windows Service, IIS, WAS, etc.) for WCF Service in a 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 the operating system.

Remember, in previous WCF Tutorial, we have already implemented WCF Self Hosting in a Console Application with an 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 its 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 the 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.

    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: Don't 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 the 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

The post WCF Hosting in Windows Service Simplified appeared first on WCF Tutorial.

License

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

Share

About the Author

Imran Abdul Ghani
Software Developer (Senior) Emaratech
United Arab Emirates United Arab Emirates
Imran Abdul Ghani has more than 10 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 WCF Tutorials, Web Development, SharePoint for Dummies.

You may also be interested in...

Pro

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170118.1 | Last Updated 16 Jun 2014
Article Copyright 2014 by Imran Abdul Ghani
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid