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
2.In Windows Service project - right click on Service.cs[design] – select add installer
3. Right-click on service process installer – properties
Select Modifiers as Public and Account as LocalSystem
4. In serviceinstaller1 - properties change service name(TestService) , also change the start typeset as Manual and Save.
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
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
9. Write a start and stop method or replace Service1.cs with the below code
- 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.Threading.Tasks;
- using System.ServiceModel;
-
- namespace WindowsService
- {
- public partial class Service1 : ServiceBase
- {
- internal static ServiceHost hostService = null;
- public Service1()
- {
- InitializeComponent();
- }
-
- protected override void OnStart(string[] args)
- {
- try
- {
- hostService = new ServiceHost(typeof(WcfServiceLibrary.Service1));
- WcfServiceLibrary.Service1 mgmtService = new WcfServiceLibrary.Service1();
- hostService.Open();
- }
- catch (Exception ex)
- {
- throw new Exception(ex.Message);
- }
- }
-
- protected override void OnStop()
- {
- hostService.Close();
- }
- }
- }
10. Add below script in App.config of WindowsService
- <?xml version="1.0" encoding="utf-8" ?>
- <configuration>
- <startup>
- <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
- </startup>
- <system.web>
- <compilation debug="true" />
- <membership defaultProvider="ClientAuthenticationMembershipProvider">
- <providers>
- <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
- </providers>
- </membership>
- <roleManager defaultProvider="ClientRoleProvider" enabled="true">
- <providers>
- <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
- </providers>
- </roleManager>
- </system.web>
-
- <system.serviceModel>
- <diagnostics>
- <messageLogging logEntireMessage="true" logKnownPii="true" logMalformedMessages="true" logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" />
- <endToEndTracing propagateActivity="true" activityTracing="true" messageFlowTracing="true" />
- </diagnostics>
- <bindings>
- <basicHttpBinding>
- <binding name="basicSecureBinding" maxBufferPoolSize="1000000" maxReceivedMessageSize="1000000">
- <readerQuotas maxDepth="1000000" maxArrayLength="1000000" maxBytesPerRead="1000000" />
- <security mode="TransportWithMessageCredential">
- <message clientCredentialType="UserName" />
- </security>
- </binding>
- </basicHttpBinding>
- </bindings>
- <services>
- <service name="WcfServiceLibrary.Service1">
- <!--<endpoint address="" binding="basicHttpBinding" bindingNamespace="http://enterurlhere/" contract="WcfServiceLibrary.IService1">
- <identity>
- <dns value="localhost" />
- </identity>
- </endpoint>
- <endpoint address="mex" binding="mexHttpBinding" bindingNamespace="http://enterurlhere/" contract="IMetadataExchange" />-->
- <host>
- <baseAddresses>
- <add baseAddress="http://localhost:8733/Design_Time_Addresses/WcfServiceLibrary/Service1/" />
- </baseAddresses>
- </host>
- </service>
- </services>
- <behaviors>
- <serviceBehaviors>
- <behavior>
- <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
- <serviceDebug includeExceptionDetailInFaults="true" />
- </behavior>
- </serviceBehaviors>
- </behaviors>
- <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
- </system.serviceModel>
- <runtime>
- <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
- <dependentAssembly>
- <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
- <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
- </dependentAssembly>
- <dependentAssembly>
- <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
- <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
- </dependentAssembly>
- </assemblyBinding>
- </runtime>
- </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
12.Right-click on setup project name - View - Custom action
Right-click on custom action - add custom actions - application folder-
Add output - Primary output – In project dropdown select WindowsService - Ok – Ok
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
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
3. Write down the below code in your program.cs file:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace CallWcfWinService
- {
- class Program
- {
- public static void Main(string[] args)
- {
- try
- {
- ServiceReference1.Service1Client objServive = new ServiceReference1.Service1Client();
- ServiceReference1.CompositeType objComposite = new ServiceReference1.CompositeType();
-
- objComposite.BoolValue = true;
- objComposite.StringValue = "Hello World";
-
- ServiceReference1.CompositeType obj = objServive.GetDataUsingDataContract(objComposite);
- string output = obj.StringValue;
-
- Console.WriteLine("Output: " + output);
- }
- catch (Exception ex)
- {
- string message = ex.Message;
- throw;
- }
- finally
- {
- Console.ReadKey();
- }
- }
-
- }
- }
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)
2. Now debug the console application, line by line
You can see the output below.
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.