This project is read-only.

How to Host WCF in a Windows Service

- J.D. Meier, Carlos Farre, Jason Taylor, Prashant Bansode, Steve Gregersen, Madhu Sundararajan, Rob Boucher

You should use a Windows service when you have to support transports like TCP, MSMQ, named pipes. Windows services have advantages over self hosting in that they give the benefit of automatic startup, service lifetime is controlled by the operating system, it is easier to run under a least privileged account and the Windows service host will restart your service if it fails. Windows services can be managed in the Service Control Manager in the Microsoft Management Console (MMC).

Use the following steps to host your WCF service in a Windows Service.
  1. Create a Windows Service Project using Visual Studio 2008
  2. Add service installers to the Windows Service Project
  3. Override OnStart and OnStop methods to Start and stop the service inside the Windows Service, as shown in the following code example.
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;

namespace WindowsService1
{
    public partial class WCFServiceHost1 : ServiceBase
    {
        internal static ServiceHost myServiceHost = null; 

        public WCFServiceHost1()
        {
            InitializeComponent();
        }
        protected override void OnStart(string[] args)
        {
            if (myServiceHost != null)
            {
                myServiceHost.Close();
            }
            myServiceHost = new ServiceHost(typeof(Service1));
            myServiceHost.Open();
        }
        protected override void OnStop()
        {
            if (myServiceHost != null)
            {
                myServiceHost.Close();
                myServiceHost = null;
            }
        }
    }
}
  1. Install the Windows service using the InstallUtil.exe command from the Visual Studio 2008 command prompt.

Additional Resources

Last edited Jun 13, 2008 at 8:01 PM by prashantbansode, version 1

Comments

No comments yet.