Friday, 14 October 2011

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.

No comments:

Post a Comment