How to Create and Consume a WCF Windows Service

Introduction

 
What exactly is a Windows service? Windows services are the applications that are running in the background. These services can be automatically started when the computer boots, can be paused and restarted, and do not show any user interface. These features make services ideal for use on a server or whenever you need long-running functionality that does not interfere with other users who are working on the same computer.
 

What is WCF?

 
Windows Communication Foundation (WCF) is a framework for building service-oriented applications Using WCF, you can send data as asynchronous messages from one service endpoint to another.
 

Endpoints

 
A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application. An endpoint can be a client of a service that requests data from a service endpoint.
 
An endpoint consists of an Address, a Binding, and a Contract (ABC)
  • An address that indicates where the endpoint can be found.
  • A binding that specifies how a client can communicate with the endpoint.
  • A contract that identifies the operations available.
For more information, you can check out the below link:
https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/endpoints-addresses-bindings-and-contracts
 

How to create a WCF Windows service

 
1.Create a new project - Select Windows Service – rename as WindowsService
 
Create windows service
 
2.In Windows Service project - right click on Service.cs[design] – select add installer
 
Add installer in windows service  
 
3. Right-click on service process installer – properties
 
Select Modifiers as Public and Account as LocalSystem
 
Change modifiers and account 
 
4. In serviceinstaller1 - properties change service name(TestService) , also change the start typeset as Manual and Save.
 
Change start type of windows service 
 
5. Now Right Click on the solution (Solution ‘WindowsService’) – Add- New Project – Select WCF - Add WCF Service Library and rename as WcfServiceLibrary
 
6. Now build Build WCF service library project(WcfServiceLibrary)
 
7. And add WCF service library reference in windows service(WindowsService)(bin - .dll)
 
WindowsService – Right click on References – Add Reference – Browse –Select WcfServiceLibrary.dll – Click Ok
 
 Add WCF service library reference in windows service Service references 
 
8. In Windows service project click on Service1.cs - click on - click here to switch to code view - add namespace of wcf service library (using WcfServiceLibrary)
 
Also, add a reference of System.ServiceModel
 
 Add reference of System.ServiceModel
 
9. Write a start and stop method or replace Service1.cs with the below code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Diagnostics;  
  6. using System.Linq;  
  7. using System.ServiceProcess;  
  8. using System.Text;  
  9. using System.Threading.Tasks;  
  10. using System.ServiceModel;  
  11.   
  12. namespace WindowsService  
  13. {  
  14.     public partial class Service1 : ServiceBase  
  15.     {  
  16.         internal static ServiceHost hostService = null;  
  17.         public Service1()  
  18.         {  
  19.             InitializeComponent();  
  20.         }  
  21.   
  22.         protected override void OnStart(string[] args)  
  23.         {  
  24.             try  
  25.             {  
  26.                 hostService = new ServiceHost(typeof(WcfServiceLibrary.Service1));  
  27.                 WcfServiceLibrary.Service1 mgmtService = new WcfServiceLibrary.Service1();  
  28.                 hostService.Open();  
  29.             }  
  30.             catch (Exception ex)  
  31.             {  
  32.                 throw new Exception(ex.Message);  
  33.             }  
  34.         }  
  35.   
  36.         protected override void OnStop()  
  37.         {  
  38.             hostService.Close();  
  39.         }  
  40.     }  
  41. }  
10. Add below script in App.config of WindowsService
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <configuration>  
  3.   <startup>  
  4.     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />  
  5.   </startup>  
  6.   <system.web>  
  7.     <compilation debug="true" />  
  8.     <membership defaultProvider="ClientAuthenticationMembershipProvider">  
  9.       <providers>  
  10.         <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />  
  11.       </providers>  
  12.     </membership>  
  13.     <roleManager defaultProvider="ClientRoleProvider" enabled="true">  
  14.       <providers>  
  15.         <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />  
  16.       </providers>  
  17.     </roleManager>  
  18.   </system.web>  
  19.   
  20.   <system.serviceModel>  
  21.     <diagnostics>  
  22.       <messageLogging logEntireMessage="true" logKnownPii="true" logMalformedMessages="true" logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" />  
  23.       <endToEndTracing propagateActivity="true" activityTracing="true" messageFlowTracing="true" />  
  24.     </diagnostics>  
  25.     <bindings>  
  26.       <basicHttpBinding>  
  27.         <binding name="basicSecureBinding" maxBufferPoolSize="1000000" maxReceivedMessageSize="1000000">  
  28.           <readerQuotas maxDepth="1000000" maxArrayLength="1000000" maxBytesPerRead="1000000" />  
  29.           <security mode="TransportWithMessageCredential">  
  30.             <message clientCredentialType="UserName" />  
  31.           </security>  
  32.         </binding>  
  33.       </basicHttpBinding>  
  34.     </bindings>  
  35.     <services>  
  36.       <service name="WcfServiceLibrary.Service1">  
  37. <!--<endpoint address="" binding="basicHttpBinding" bindingNamespace="http://enterurlhere/" contract="WcfServiceLibrary.IService1">  
  38.           <identity>  
  39.             <dns value="localhost" />  
  40.           </identity>  
  41.         </endpoint>  
  42.         <endpoint address="mex" binding="mexHttpBinding" bindingNamespace="http://enterurlhere/" contract="IMetadataExchange" />-->  
  43.         <host>  
  44.           <baseAddresses>  
  45.             <add baseAddress="http://localhost:8733/Design_Time_Addresses/WcfServiceLibrary/Service1/" />  
  46.           </baseAddresses>  
  47.         </host>  
  48.       </service>  
  49.     </services>  
  50.     <behaviors>  
  51.       <serviceBehaviors>  
  52.         <behavior>  
  53.           <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />  
  54.           <serviceDebug includeExceptionDetailInFaults="true" />  
  55.         </behavior>  
  56.       </serviceBehaviors>  
  57.     </behaviors>  
  58.     <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />  
  59.   </system.serviceModel>  
  60.   <runtime>  
  61.     <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">  
  62.       <dependentAssembly>  
  63.         <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />  
  64.         <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />  
  65.       </dependentAssembly>  
  66.       <dependentAssembly>  
  67.         <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />  
  68.         <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />  
  69.       </dependentAssembly>  
  70.     </assemblyBinding>  
  71.   </runtime>  
  72. </configuration>  
11. Build your Windows service project
 
Now right-click on the solution (Solution ‘WindowsService’) – Add- New Project – Click on Other Project Types tab – Select Setup Project – Rename as WcfWinServiceSetup
 
 Create setup project
 
12.Right-click on setup project name - View - Custom action
 
 Custom action in setup project
 
Right-click on custom action - add custom actions - application folder-
 
Custom action popup
 
Add output - Primary output – In project dropdown select WindowsService - Ok – Ok
 
Primary output in custom action
 
13.Now build the setup project
 
The file will generate in your debug or release folder
 
Now Install the setup project – you can install the setup project by double click on setup.exe file
 
Or in the solution right-click on WcfWinServiceSetup and click on Install- click next – select radio button Everyone – Next – Next – after Install Complete click close
 
14.Start the service - Start menu - services - right click on the service name(TestService) - start service.
 

How to consume a WCF windows service through a console application

 
1. Create a new Console Application and rename as CallWcfWinService
 
Create new console application
 
2. Add service reference - Copy baseAdddress from app.config file of WcfServiceLibrary in my case it is http://localhost:8733/Design_Time_Addresses/WcfServiceLibrary/Service1/
 
Right-click on References – Add service references – In address – Add baseaddress(http://localhost:8733/Design_Time_Addresses/WcfServiceLibrary/Service1/)
 
Click on Go – You can see the below screen – Click OK
 
Add windows service reference 
 
3. Write down the below code in your program.cs file:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace CallWcfWinService  
  8. {  
  9.     class Program  
  10.     {  
  11.         public static void Main(string[] args)  
  12.         {  
  13.             try  
  14.             {  
  15.                 ServiceReference1.Service1Client objServive = new ServiceReference1.Service1Client();  
  16.                 ServiceReference1.CompositeType objComposite = new ServiceReference1.CompositeType();  
  17.   
  18.                 objComposite.BoolValue = true;  
  19.                 objComposite.StringValue = "Hello World";  
  20.   
  21.                 ServiceReference1.CompositeType obj = objServive.GetDataUsingDataContract(objComposite);  
  22.                 string output = obj.StringValue;  
  23.   
  24.                 Console.WriteLine("Output: " + output);  
  25.             }  
  26.             catch (Exception ex)  
  27.             {  
  28.                 string message = ex.Message;  
  29.                 throw;  
  30.             }  
  31.             finally  
  32.             {  
  33.                 Console.ReadKey();  
  34.             }  
  35.         }  
  36.   
  37.     }  
  38. }  

How to debug windows service using a console application

 
1. In windows service solution click on debug in the main menu - attach process which has service name .exe (WindowsService.exe)
 
Attach process in windows service
 
2. Now debug the console application, line by line
 
You can see the output below.
 
Output screen
 

Summary

 
In this blog, you learned how to create a WCF Windows Service, how to create a setup project, and finally, how to consume a WCF Windows service in a console application.
 
Thank you for reading.