.NET Zone is brought to you in partnership with:

I am developer and technology maniac who is working on Microsoft and PHP technologies. I have ASP.NET MVP title and I hold MCAD, MCSD and MCTS certificates. When I have free time I usually play with new technologies, hack something, read books, participate in communities and speak in events. I am also active blogger and my ASP.NET blog is the place you can find some interesting reading about my discoveries and personal thoughts. Gunnar is a DZone MVB and is not an employee of DZone and has posted 142 posts at DZone. You can read more from them at their website. View Full User Profile

Hosting WCF Services In A Windows Service

08.24.2012
| 6388 views |
  • submit to reddit

When building Windows services we often need a way to communicate with them. The natural way to communicate to service is to send signals to it. But this is very limited communication. Usually we need more powerful communication mechanisms with services. In this posting I will show you how to use service-hosted WCF web service to communicate with Windows service.

Create Windows service

 Create Windows service

Suppose you have Windows service created and service class is named as MyWindowsService. This is new service and all we have is default code that Visual Studio generates.

Create WCF service

Add reference to System.ServiceModel assembly to Windows service project and add new interface called IMyService. This interface defines our service contracts.

[ServiceContract]
public interface IMyService
{
    [OperationContract]
    string SayHello(int value);
}

We keep this service simple so it is easy for you to follow the code. Now let’s add service implementation:

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class MyService : IMyService
{
   public string SayHello(int value)
    {
        return string.Format("Hello, : {0}", value);
    }
}

With ServiceBehavior attribute we say that we need only one instance of WCF service to serve all requests. Usually this is more than enough for us.

Hosting WCF service in Windows Service

Now it’s time to host our WCF service and make it available in Windows service. Here is the code in my Windows service:

public partial class MyWindowsService : ServiceBase
{
    private ServiceHost _host;
    private MyService _server;
 
    public MyWindowsService()
    {
        InitializeComponent();
    }
 
    protected override void OnStart(string[] args)
    {
       _server = new MyService();
        _host = new ServiceHost(_server);
        _host.Open();
   }
 
    protected override void OnStop()
    {
       _host.Close();     }
}

Our Windows service now hosts our WCF service. WCF service will be available when Windows service is started and it is taken down when Windows service stops.

Configuring WCF service

To make WCF service usable we need to configure it. Add app.config file to your Windows service project and paste the following XML there:

<system.serviceModel>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
  <services>
    <service name="MyWindowsService.MyService" behaviorConfiguration="def">
      <host>
        <baseAddresses>
          <add baseAddress="http://localhost:8732/MyService/"/>
        </baseAddresses>
      </host>
      <endpoint address="" binding="wsHttpBinding" contract="MyWindowsService.IMyService">
      </endpoint>
      <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
    </service>
  </services>
  <behaviors>
    <serviceBehaviors>
      <behavior name="def">
        <serviceMetadata httpGetEnabled="True"/>
        <serviceDebug includeExceptionDetailInFaults="True"/>
      </behavior>
    </serviceBehaviors>
  </behaviors>
</system.serviceModel>

Now you are ready to test your service. Install Windows service and start it. Open your browser and open the following address: http://localhost:8732/MyService/ You should see your WCF service page now.

Conclusion

WCF is not only web applications fun. You can use WCF also as self-hosted service. Windows services that lack good communication possibilities can be saved by using WCF self-hosted service as it is the best way to talk to service. We can also revert the context and say that Windows service is good host for our WCF service.

Published at DZone with permission of Gunnar Peipman, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)