Hosting a WCF Service Inside a Windows Service | CodeGuru

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 […]

Written By
Hannes DuPreez
Hannes DuPreez
Jan 4, 2016
2 minute read
CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More

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.

Advertisement

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.

Advertisement

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!

Hannes DuPreez

Ockert J. du Preez is a passionate coder and always willing to learn. He has written hundreds of developer articles over the years detailing his programming quests and adventures. He has written the following books: Visual Studio 2019 In-Depth (BpB Publications) JavaScript for Gurus (BpB Publications) He was the Technical Editor for Professional C++, 5th Edition (Wiley) He was a Microsoft Most Valuable Professional for .NET (2008–2017).

CodeGuru Logo

CodeGuru covers topics related to Microsoft-related software development, mobile development, database management, and web application programming. In addition to tutorials and how-tos that teach programmers how to code in Microsoft-related languages and frameworks like C# and .Net, we also publish articles on software development tools, the latest in developer news, and advice for project managers. Cloud services such as Microsoft Azure and database options including SQL Server and MSSQL are also frequently covered.

Property of TechnologyAdvice. © 2026 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.