Feb
8
2012

C#.Net How To: Host a WCF Service in Windows Service using VS 2010

In this WCF tutorial let’s learn to host WCF service in Windows Service. A WCF service can be hosted in IIS, Windows Services, Windows Activation Service (WAS) and It also supports Self-hosting. In one of my previous article I have explained how to Host WCF service in IIS.

Before we learn the process of hosting wcf service in windows service, we should know the what is windows service? and how it works?.

What is Windows Service?

A windows service is a process managed by the Windows Operating System. Windows operating system always comes with the Service Control Manager, which controls various services installed on operating system of that machine.

Following are the main advantages using Managed Windows Service for WCF hosting

  1. When system starts, the service will host automatically.
  2. All versions of windows support hosting WCF service.
  3. Service Control Manager controls the process life time of the service.
  4. To host your WCF service inside a Windows service, you merely have to implement the Start() and Stop() methods of the Windows service.

This tutorial contains following steps to learn how to host WCF service in Windows Service

  1. Create a new console application and implement WCF service in it.
  2. Create a new Windows Service project & add it to WCF service.
  3. Create a new Setup and Deployment (Installer) project to the solution.

The goal of this c# tutorial is to create a WCF service, host wcf service in windows service and then returns a WelCome message through a method.

Create a new console application and implement WCF service in it.

  1. Create a new console application project. Enter the project name and click OK button. Here, I have specified the project name as “WCFWindowsServiceHosting“.
    WCF service in Windows Service - Console Application
    WCF in Windows Service – Console Application
  2. Rename the file Program.cs to Welcome.cs and make it a public class. We will implement the service contract in this class later.
  3. Now add following three references –
    1. System.ServiceModel.dll
    2. System.ServiceProcess.dll
    3. System.Configuration.Install.dll
    WCF in Windows Service - Adding References
    WCF in Windows Service – Adding References
  4. Now as part of the WCF service, we will required to define the Service Contract. Add a new interface named as “IWelcome” that will act as service contract.
    WCF in Windows Service - Adding New Class
    WCF in Windows Service – New Class
    WCF in Windows Service - Adding New Interface
    WCF in Windows Service – Adding New Interface

    Name this Interface as as IWelcome and click on Add button.

  5. Add following line in both Welcome.cs and IWelcome.cs files.
    using System.ServiceModel;
  6. Add following code to the Service Contract i.e. IWelcome.cs
    using System.ServiceModel;
    namespace WCFWindowsServiceHosting
    {
         //Define a service contract.
        [ServiceContract(Namespace=“http://WCFWindowsServiceHosting”)]
        public interface IWelcome
        {
            [OperationContract]
            String WelcomeMessage(String name);
        }
    }
  7. Now implement the service contract. Go to Welcome.cs file, remove the main() method and add following code –
    using System.ServiceModel;
    namespace WCFWindowsServiceHosting
    {
        public class Welcome : IWelcome
        {
            //Implement service contract.
            public String WelcomeMessage(String name)
            {
                return String.Format(“Welcome to http://www.csharptutorial.in, {0}”, name);
            }
        }
    }

    The coding part of WCF service implementation is completed. The next step is to create a windows service to host WCF service in Windows Service.

Create a new Windows Service project & add it to WCF service.

  1. To create a new windows service, right click on your project name; in our case it is “WCFWindowsServiceHosting” and click on Add -> New Item or Press Ctrl+Shift+A.
    WCF in Windows Service - Windows Service Project
    WCF in Windows Service – Windows Service Project

    Select Windows Service, name it as “WCFWindowsService” and click on Add button.

  2. You will get the designer view. Click on “Click here to switch to code view“. Look at the code, WCFWindowsService class is inherited from ServiceBase class. To qualify as a Windows Service, the class inherits from the ServiceBase class and implements the OnStart and OnStop methods. Because the paradigm of starting Windows services is similar to starting your services inside WCF ServiceHost, you end up tying the lifetime of your WCF service to the lifetime of your Windows service.
  3. Make the WCFWindowsService class public and add following line to the code.
    using System.ServiceModel;
  4. Add ServiceHost –
    public ServiceHost serviceHost = null;
  5. Now implement the OnStart method as shown below –
            protected override void OnStart(string[] args)
            {
                if (serviceHost != null)
                    serviceHost.Close();
                serviceHost = new ServiceHost(typeof(Welcome));
                serviceHost.Open();
            }
  6. Implement the OnStop method as shown below –
            protected override void OnStop()
            {
                if (serviceHost != null)
                {
                    serviceHost.Close();
                    serviceHost = null;
                }
            }
  7. The final code will look like –
    using System.ServiceModel;
    namespace WCFWindowsServiceHosting
    {
        public partial class WCFWindowsService : ServiceBase
        {
            public ServiceHost serviceHost = null;
            public WCFWindowsService()
            {
                InitializeComponent();
            }
            protected override void OnStart(string[] args)
            {
                if (serviceHost != null)
                    serviceHost.Close();
                serviceHost = new ServiceHost(typeof(Welcome));
                serviceHost.Open();
            }
            protected override void OnStop()
            {
                if (serviceHost != null)
                {
                    serviceHost.Close();
                    serviceHost = null;
                }
            }
        }
    }
  8. To host wcf service in windows service, we need to add Configuration file i.e app.config to define the end points. Right click on project “WCFWindowsServiceHosting” and select Add and New items. Select “Application Configuration File“. And click on Add button.
    WCF in Windows Service - App.config
    WCF in Windows Service – App.config
  9. Copy below code and paste it in App.config file –
    <?xml version=1.0 encoding=utf-8 ?>
    <configuration>
      <system.serviceModel>
        <services>
          <!– This section is optional with the new configuration model
               introduced in .NET Framework 4. –>
          <service name=WCFWindowsServiceHosting.Welcome
                   behaviorConfiguration=MyServiceBehavior>
            <host>
              <baseAddresses>
                <add baseAddress=http://localhost:8000/WCFWindowsServiceHosting/Welcome/>
              </baseAddresses>
            </host>
            <!– this endpoint is exposed at the base address provided by host: http://localhost:8000/WCFWindowsServiceHosting/Welcome –>
            <endpoint address=“”
                      binding=wsHttpBinding
                      contract=WCFWindowsServiceHosting.IWelcome />
            <!– the mex endpoint is exposed at http://localhost:8000/WCFWindowsServiceHosting/Welcome/mex –>
            <endpoint address=mex
                      binding=mexHttpBinding
                      contract=IMetadataExchange />
          </service>
        </services>
        <behaviors>
          <serviceBehaviors>
            <behavior name=MyServiceBehavior>
              <serviceMetadata httpGetEnabled=true/>
              <serviceDebug includeExceptionDetailInFaults=False/>
            </behavior>
          </serviceBehaviors>
        </behaviors>
      </system.serviceModel>
    </configuration>

    The Windows Service code is completed. The next step is to add the windows service installer to the project. Once service will be ready and running you will access the service by URL “http://localhost:8000/WCFWindowsServiceHosting/Welcome“.

Create a new Setup and Deployment (Installer) project to the solution.

  1. To be able to install a service in the Service Control Manager, you have to add windows service installer to the project. To add windows service installer, open designer view WCFWindowsServices class view, right click on the background of the view and select Add Installer property.
    WCF in Windows Service - Windows Service Installer
    WCF in Windows Service – Windows Service Installer
  2. A ProjectInstaller.cs will get added into the solution explorer.
    WCF in Windows Service - ProjectInstaller.cs
    WCF in Windows Service – ProjectInstaller.cs
  3. Open the designer view of ProjectInstaller, then right click on serviceInstaller1 and select properties property to open the property window of ServiceInstaller1.
    WCF in Windows Service - ProjectInstaller.cs Design View
    WCF in Windows Service – ProjectInstaller.cs Design View
    WCF in Windows Service - ServiceInstaller.cs Properties
    WCF in Windows Service – ServiceInstaller.cs Properties
  4. Set the StartType to Automatic, so that the service gets started automatically every time the machine gets started.
    WCF in Windows Service - ServiceInstaller StartType
    WCF in Windows Service – ServiceInstaller StartType

    The windows service installer code is completed. Now we will required a setup that can install the Windows Service in a machine. The next steps will describe how to add a Visual Studio Setup and Deployment project to the solution.

  5. Select File -> Add -> New Project
    WCF - Setup & Deployment Project
    WCF in Windows Service – Setup & Deployment Project
  6. Go to Visual Studio Installer from Installed Templates and then select Setup project.
    WCF in Windows Service - Setup
    WCF in Windows Service – Setup

    Select the location and Click on Ok button.

  7. In the solution explorer, right click on Setup project, go to Add and select Project Output…
    WCF in Windows Service - Setup Custom Actions
    WCF in Windows Service – Setup Custom Actions
  8. Select the Project “WCFWindowsServiceHosting“. Now select Primary Output and click on OK button.
    WCF in Windows Service - Setup output group
    WCF in Windows Service – Setup output group

    This will add a project item for the primary output of windows service to the setup project. The next step is to add custom actions to the executable file. These custom actions are Install, Commit, Rollback and Uninstall.

  9. To add the custom actions, right click on setup1 project in solution explorer, goto View and select Custom Actions.
    WCF in Windows Service - Project Output
    WCF in Windows Service – Project Output
  10. The custom action view appears
    WCF in Windows Service - Custom Actions Setup
    WCF in Windows Service – Custom Actions Setup
  11. Right click on Custom Actions and select Add Custom Action..
    WCF in Windows Service - Adding Custom Actions
    WCF in Windows Service – Adding Custom Actions
  12. A custom action – Select Item in Project window appears.
    WCF in Windows Service -Setting items in Setup
    WCF in Windows Service -Setting items in Setup
  13. Double click on Application Folder in list box. Select Primary output from WCFWindowsServiceHosting and click on OK button.
    WCF in Windows Service -Setting items in Project
    WCF in Windows Service -Setting items in Project

    This will add Primary output from WCFWindowsServiceHosting to all custom actions.

    WCF in Windows Service - All Custom Actions
    WCF in Windows Service – All Custom Actions

    The installer project is completed. Now build both project i.e “WCFWindowsServiceHosting” and “Setup1” to get the .msi in debug folder of Setup1 physical location.

  14. Goto debug folder of “Setup1” project and install Setup1.msi. After successful installation of the Setup1, a service “Setup1” will add in the windows services. Open task manager and check the Services tab. You will get “WCFWindowsService” added in services. Right click on service and click on Start Service to start the service.
    WCF service in Windows Service
    WCF hosted in Windows Service
  15. Once service is started, either you can access the WCF service by entering http://localhost:8000/WCFWindowsServiceHosting/Welcome in internet browser or you can consume wcf service.

In this wcf tutorial we learn to host a WCF Service in Windows Service using VS 2010.

I hope you enjoyed the article. If you find this article helpful, then could you please share the article on your social media?

More interesting WCF tutorials for you below…

About the Author: Ashish Ramteke

Ashish Ramteke is a Software Professional, Part time blogger and founder of C# Tutorials, a popular blog on C#.Net. Ashish is having 6 years of work experience and an engineering degree in Computer Science and Engg.

14 Comments+ Add Comment

  • Thanks Ashish.
    Keep posting…

    -Abhijeet

  • There are lots of web articles on WCF, but are very confusing. Here is a simple and understandable article. Screenshots at every steps makes it very clear. Thanks a lot Ashish.
    All the best and Keep posting…

  • Thanks alot for this clear tutorial..
    I have some questions;
    how can i use the methods from explorer and how can i publish this service over the internet?

    • I have followed the steps for this tutorial but I get an issue when i build, it complains that there is no entry point for “Main”
      Under Project properties there is no Startup Object

      thanks in advance

      Damian

    • Hi have the same error. How you solved the problem about main method? Thanks.

    • Pls add main method to WCFWindowsService.cs file. So the final code of this file looks :

      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 WCFWindowsServiceHosting
      {
      public partial class WCFWindowsService : ServiceBase
      {
      public ServiceHost serviceHost = null;

      public WCFWindowsService()
      {
      InitializeComponent();
      }

      protected override void OnStart(string[] args)
      {
      if (serviceHost != null)
      serviceHost.Close();

      serviceHost = new ServiceHost(typeof(Welcome));
      serviceHost.Open();
      }

      protected override void OnStop()
      {
      if (serviceHost != null)
      {
      serviceHost.Close();
      serviceHost = null;
      }
      }
      }

      static class HariProgram
      {
      static void Main(string[] args)
      {
      ServiceBase[] ServicesToRun;
      ServicesToRun = new ServiceBase[] { new WCFWindowsService() };
      ServiceBase.Run(ServicesToRun);

      }
      }
      }

      ***********************
      My name is Harikrushna Trivedi
      Email id : harikrushna.trivedi@ril.com

    • Very nice article but on installing the setup1.msi it is asking for user name and password. what should i give as user name and password

  • I utterly attitude and revalue your bushel on each and every target.
    hostinghq.ca

  • Good one, Keep Posting more
    Thanks

  • I have been searching for hours and I haven’t found such awesome work.
    Hoster Talk

  • Hello, great Tutorial…

    but I have one Problem. When I want start the Service in services.msc, a message like “Error 1053: The service did not respond to the start or control request in a timely fashion” appears. Has someone any idea where my configuration isn’t correct?

  • Wonderful..Great goods . If you want to learn about features of asp hosting reviews then you can touch on that. You can also visit: http://www.mywindowshosting.com

  • Nice to read your post!!! Well the two and most important factors for $1 Web Hosting are the actual computer space that’s allotted for website files and also the speed at which a person can access those files when they are trying to access them using the Internet.

  • awesome article…..

Leave a comment