Hosting a WCF Service Inside a Windows Service

Introduction

Services: We all love them, but we all hate them. WCF services can get quite tricky because they are so sensitive, but once you get the hang of them, they can become very easy, very quickly. Today, you will learn how to host a WCF RESTFul service inside a Windows Service.

WCF

The Windows Communication Foundation (WCF) enables you to build service-oriented applications. Service-oriented applications mean that you have a back-end and a front-end communicating successfully with one another. The back-end is the physical service that reads messages, or data from a source that can be another WCF service, a Windows Service, a Web site, or even a mobile phone. The messages between the front-end and back-end are sent asynchronously. Data that can be sent from and to the service can be in XML or Raw format; in other words, binary data, and JSON. Here is more information on WCF.

Windows Services

Here is some information on Windows Services.

REST

REST is not tied to any particular technology or platform. It's simply a way to design things to work like the Web.

Our Project

Create a new Windows Service project in Visual Basic. You may name it anything you want. Keep in mind, though, that I have named mine 'TestService'.

Create a common Namespace above the Class declaration of TestService.

Namespace TestService

Create the TestService class:

   <ServiceBehavior(InstanceContextMode:= _
      InstanceContextMode.PerSession)> _
   Public Class TestService
      Inherits ServiceBase
      Public serviceHost As ServiceHost = Nothing

      Public Shared Sub Main()
         ServiceBase.Run(New TestService())
      End Sub

      Public Sub New()
         ServiceName = "Test Service"
      End Sub

      'Start the Windows service.
      Protected Overloads Overrides Sub OnStart(ByVal args _
            As String())
         Try
            If serviceHost IsNot Nothing Then
               serviceHost.Close()
            End If

            serviceHost = New WebServiceHost(GetType(cTestService), _
               New Uri("http://localhost/TestService"))
            serviceHost.AddServiceEndpoint(GetType(ITestService), _
               New WebHttpBinding(), "http://localhost/TestService")

            serviceHost.Open()


         Catch ex As Exception
            System.Diagnostics.EventLog.WriteEntry("Test Service", _
               ex.Message, EventLogEntryType.Error)
            WebOperationContext.Current.OutgoingResponse.StatusCode = 501
            serviceHost.Close()

            End
         End Try
      End Sub

      ' Stop the Windows service.
      Protected Overloads Overrides Sub OnStop()
         If serviceHost IsNot Nothing Then
            serviceHost.Close()

            serviceHost = Nothing

         End If
      End Sub
   End Class

Here, you create the TestService class, which is the Windows Service that will spawn the WCF Service from within. You specify how the service should behave via the ServiceBehaviour setting.

You created the onStart and OnStop events to set up the service and specify its associated EndPoints.

EndPoints

Endpoints provide clients with access to the functionality a Windows Communication Foundation (WCF) service offers. You can define one or more endpoints for a service by using a combination of relative and absolute endpoint addresses, or if you do not define any service endpoints, the runtime provides some by default for you. This topic shows how to add endpoints using a configuration file that contain both relative and absolute addresses.

Add the following code to give the WCF Service some work to do:

   <AspNetCompatibilityRequirements(Requirementsmode:= _
      AspNetCompatibilityRequirementsMode.Allowed)> _
   Public Class cTestService
      Inherits System.Web.Services.WebService
      Implements ITestService

      Function GetCustomers() As Stream Implements _
            ITestService.GetCustomers
         Try

         'Do what you want here

         'Successful
         WebOperationContext.Current.OutgoingResponse.StatusCode = 200
         WebOperationContext.Current.OutgoingResponse.StatusDescription _
            = "OK"


         Catch ex As Exception
            System.Diagnostics.EventLog.WriteEntry("Test Service", _
               ex.Message, EventLogEntryType.Error)

            WebOperationContext.Current.OutgoingResponse.StatusCode = 501
            WebOperationContext.Current.OutgoingResponse.StatusDescription _
               = ex.Message

         End Try
      End Function


   End Class

This is just a skeleton, as you can see, but it demonstrates how you should populate the WCF Service with a method. All that is needed now is to create an Interface for the GetCustomers method.

Add a new class and add the following code into it:

Imports System.ServiceModel.Web
Imports System.ServiceModel.Channels
Imports System.Text
Imports System.IO

Namespace TestService
   <ServiceContract()> _
   Public Interface ITestService


      <OperationContract()> _
         <WebGet(BodyStyle:=WebMessageBodyStyle.Bare, _
            ResponseFormat:=WebMessageFormat.Json,
            RequestFormat:=WebMessageFormat.Json)> _
      Function GetCustomers() As Stream


   End Interface


End Namespace

This creates a WCF Interface so that the WCF service knows which methods to expect.

You may now add a Setup & Deployment project which will allow you to install this service on any Windows system.

Conclusion

Now that you've seen an example—and you can download the code from the link below—you'll be proficient with WCF programming in no time. Until next time, cheers!



About the Author

Hannes DuPreez

Hannes du Preez is a Microsoft MVP for Visual Basic for the ninth consecutive year. He loves technology and loves Visual Basic. He loves writing articles and proving that Visual Basic is more powerful than what most believe. His ultimate dream is to write a Visual Basic book, hopefully one day that dream will come true. You are most welcome to reach him at: ojdupreez1978@gmail.com

Related Articles

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date