Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Monday, September 24, 2012

Windows Service Hosting

In this tutorial we are going to see the hosting WCF service in Windows service. We will use same set of code used for hosting the WCF service in Console application to this. This is same as hosting the service in IIS without message activated. There is some advantage of hosting service in Windows service.
  • The service will be hosted, when system starts
  • Process life time of the service can be controlled by Service Control Manager for windows service
  • All versions of Windows will support hosting WCF service.
Step 1: Now let start create the WCF service, Open the Visual Studio 2008 and click New->Project and select Class Library from the template.
Step 2: Add reference System.ServiceModel to the project. This is the core assembly used for creating the WCF service.
Step 3: Next we can create the ISimpleCalulator interface as shown below. Add the Service and Operation Contract attribute as shown below.
ISimpleCalculator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace WindowsServiceHostedContract
{
    [ServiceContract]
    public interface ISimpleCalculator
    {
        [OperationContract]
        int Add(int num1, int num2);

        [OperationContract]
        int Subtract(int num1, int num2);

        [OperationContract]
        int Multiply(int num1,int num2);

        [OperationContract]
        double Divide(int num1, int num2);

    }
}
Step 4: Implement the ISimpleCalculator interface as shown below.
SimpleCalulator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WindowsServiceHostedService
{
    class SimpleCalculator
        : ISimpleCalculator
    {
 
        public int Add(int num1, int num2)
        {
            return num1+num2;
        }

        public int Subtract(int num1, int num2)
        {
             return num1-num2;
        }

        public int Multiply(int num1, int num2)
        {
             return num1*num2;
        }

        public double Divide(int num1, int num2)
        {
            if (num2 != 0)
                return num1 / num2;
            else
                return 0;
        }


    }
}
Step 5: Build the Project and get the dll. Now we are ready with WCF service, now we are going to see how to host the WCF Service in Windows service. Note: In this project, I have mention that we are creating both Contract and Service(implementation) are in same project. It is always good practice if you have both in different project.
Step 6: Open Visual Studio 2008 and Click New->Project and select Windows Service.
Step 7: Add the 'WindowsServiceHostedService.dll' as reference to the project. This assembly will going to act as service.
Step 8: OnStart method of the service, we can write the hosting code for WCF. We have to make sure that we are using only one service host object. On stop method you need to close the Service Host. Following code show how to host WCF service in Windows service.
WCFHostedWindowsService.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace WCFHostedWindowsService
{
    partial class WCFHostedWindowsService : ServiceBase
    {
        ServiceHost m_Host;
        
        public WCFHostedWindowsService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            if (m_Host != null)
            {
                m_Host.Close();
            }
            //Create a URI to serve as the base address
            Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator");
            //Create ServiceHost
            m_Host = new ServiceHost
            (typeof(WindowsServiceHostedService.SimpleCalculator), httpUrl);
            //Add a service endpoint
            m_Host.AddServiceEndpoint
            (typeof(WindowsServiceHostedService.ISimpleCalculator), new WSHttpBinding(), "");
            //Enable metadata exchange
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            m_Host.Description.Behaviors.Add(smb);
            //Start the Service
            m_Host.Open();


        }

        protected override void OnStop()
        {
            if (m_Host != null)
            {
                m_Host.Close();
                m_Host = null;
            }
        }
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
   { 
    new WCFHostedWindowsService() 
   };
            ServiceBase.Run(ServicesToRun);

        }
    }
}
Step 9: In order to install the service we need to have the Installer class for the Windows service. So add new Installer class to the project, which is inherited from the Installer class. Please find the below code for mentioning the Service name, StartUp type etc of the service.
ServiceInstaller.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceProcess;
using System.Configuration.Install;
using System.ComponentModel;
using System.Configuration;


namespace WCFHostedWindowsService
{
    [RunInstaller(true)]
    public class WinServiceInstaller : Installer
    {
        private ServiceProcessInstaller process;
        private ServiceInstaller service;

        public WinServiceInstaller()
        {
            process = new ServiceProcessInstaller();
            process.Account = ServiceAccount.NetworkService;
            service = new ServiceInstaller();
            service.ServiceName = "WCFHostedWindowsService";
            service.DisplayName = "WCFHostedWindowsService";
            service.Description = "WCF Service Hosted";
            service.StartType = ServiceStartMode.Automatic;
            Installers.Add(process);
            Installers.Add(service);
        }
    }
}
Step 10: Build the project, we will get the WCFHostedWindowsService.exe. Next we need to install the service using Visual Studio Command Prompt. So open the command prompt by clicking Start->All Programs-> Microsoft Visual Studio 2008-> Visual Studio Tools-> Visual Studio Command Prompt Using installutil utility application, you can install the service as shown below.
Step 11: Now service is Hosted sucessfully and we can create the proxy class for the service and start using in the client applcaiton.

No comments:

Post a Comment