How to host WCF in a Windows service

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

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;
using WcfServiceLibrary1;

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

  • For more information see “How To - Host WCF in a Windows Service Using TCP” at <<link>>
  • For more information see “How to: Host a WCF Service in a Managed Windows Service” at http://msdn.microsoft.com/en-us/library/ms733069.aspx

Last edited May 8, 2008 at 4:49 AM by prashantbansode, version 1

Comments

No comments yet.