WCF Windows Hosting And Consuming APIs To Client Side

WCF (Windows Communication Foundation) is a technology of Microsoft that is being used to implement and deploy Service Oriented Architecture (SOA). Services can be hosted to different location or on different machine and client can consume hosted services in the form of APIs. Services can be consumed by multiple clients.

WCF provides the following four common ways of Hosting:

  1. IIS Hosting
  2. WAS Hosting
  3. Windows Hosting
  4. Self-Hosting (Hosting in Application)

I will not explain the detailed features, hosting, advantages and disadvantages of WCF, but I will explain the way of Windows hosting and consuming step by step.

Step 1: Create WCF Service Application.

WCF Service Application provides to create Operation Contract, Service Contract, Data Contract, etc. Operation contract provides methods those are being exposed to client side.

The following are the steps to create WCF Service Application:

  1. Create one empty project by Visual Studio 2013.

  2. Now, right click on the solution explorer, Add New Project, WCF, then WCF Service. Application with Project name “Servies”.

  3. Add reference "System.ServiceModel".

  4. Add One Interface "ICalculator" and write the following code:
    1. using System;    
    2. using System.Collections.Generic;    
    3. using System.Linq;    
    4. using System.ServiceModel;    
    5. using System.Text;    
    6. using System.Threading.Tasks;    
    7.     
    8. namespace Services    
    9. {    
    10.     [ServiceContract]    
    11.     public interface ICalculator    
    12.     {    
    13.         [OperationContract]    
    14.         double Add(double n1, double n2);    
    15.         [OperationContract]    
    16.         double Subtract(double n1, double n2);    
    17.         [OperationContract]    
    18.         double Multiply(double n1, double n2);    
    19.         [OperationContract]    
    20.         double Divide(double n1, double n2);    
    21.     }    
    22. }   
  5. Now, create one class “CalculatorService”. It will implement the interface “ICalculator” like the following:
    1. using System;    
    2. using System.Collections.Generic;    
    3. using System.Linq;    
    4. using System.Web;    
    5.     
    6. namespace Services    
    7. {    
    8.     public class CalculatorService : ICalculator    
    9.     {    
    10.         public double Add(double number1, double number2)    
    11.         {    
    12.             double result = number1 + number2;    
    13.             return result;    
    14.         }    
    15.     
    16.         public double Subtract(double number1, double number2)    
    17.         {    
    18.             double result = number1 - number2;    
    19.             return result;    
    20.         }    
    21.     
    22.         public double Multiply(double number1, double number2)    
    23.         {    
    24.             double result = number1 * number2;    
    25.             return result;    
    26.         }    
    27.     
    28.         public double Divide(double number1, double number2)    
    29.         {    
    30.             double result = number1 / number2;    
    31.             return result;    
    32.         }    
    33.     }    
    34. }    
  6. Rebuild the “Services” project to create dll.

Step 2: Create WCF Window Service Project.

I will explain the concept of WCF Windows hosting, so this project will contain the contract and endpoint details and it will be installed in the form of windows  service.

The following are the steps to create and host WCF window service:

  1. Right click on the solution explorer of VS 2013, Add New Project, Windows Desktop, then Windows Service.

  2. Rename the project from “Service1” to “CalculatorWindowsService”.

  3. Add reference of “Services” project.

  4. Now, open CalculatorWindowsService class - Click to switch to code view, then CalculatorWindowsService.cs and a file will open. This file contains the name of service, creates service host, starts and stops the services.

  5. Write the following code in CalculatorWindowsService.cs:
    1. using System;    
    2. using System.Collections.Generic;    
    3. using System.Linq;    
    4. using System.ServiceModel;    
    5. using System.ServiceProcess;    
    6. using System.Text;    
    7. using System.Threading.Tasks;    
    8.     
    9. namespace CalculatorWindowsService    
    10. {    
    11.     public class CalculatorWindowsService : ServiceBase    
    12.     {    
    13.         public ServiceHost serviceHost = null;    
    14.         public CalculatorWindowsService()    
    15.         {    
    16.             // Name the Windows Service    
    17.             ServiceName = "WCFWindowsServiceSample";    
    18.         }    
    19.     
    20.         // Start the Windows service.    
    21.         protected override void OnStart(string[] args)    
    22.         {    
    23.             if (serviceHost != null)    
    24.             {    
    25.                 serviceHost.Close();    
    26.             }    
    27.     
    28.             // Create a ServiceHost for the CalculatorService type and     
    29.             // provide the base address.    
    30.             serviceHost = new ServiceHost(typeof(Services.CalculatorService));    
    31.     
    32.             // Open the ServiceHostBase to create listeners and start     
    33.             // listening for messages.    
    34.             serviceHost.Open();    
    35.         }    
    36.     
    37.         protected override void OnStop()    
    38.         {    
    39.             if (serviceHost != null)    
    40.             {    
    41.                 serviceHost.Close();    
    42.                 serviceHost = null;    
    43.             }    
    44.         }    
    45.           
    46.     }    
    47. }  
  6. Right click on the project “CalculatorWindowsService” - Add New Item, Installer Class and name it “ProjectInstaller.cs”.

    Basically this class instantiates ServiceProcessInstaller and service account types like “Local System, Local Service, Network Service, User”, Assign the Account to LocalSystem.

    ServiceInstaller is being instantiated for defining the name of service.

    This class adds ServiceProcessInstaller and Service which contains all information.

    Here's the code:
    1. [RunInstaller(true)]    
    2. public partial class ProjectInstaller : System.Configuration.Install.Installer    
    3. {    
    4.     private ServiceProcessInstaller process;    
    5.     private ServiceInstaller service;    
    6.     public ProjectInstaller()    
    7.     {    
    8.         InitializeComponent();    
    9.         process = new ServiceProcessInstaller();    
    10.         process.Account = ServiceAccount.LocalSystem;    
    11.         service = new ServiceInstaller();    
    12.         service.ServiceName = "WCFWindowsServiceSample";    
    13.         Installers.Add(process);    
    14.         Installers.Add(service);    
    15.     }    
    16. }    
  7. Now, open “Program” file to run the services. Write the following code:
    1. static class Program    
    2. {    
    3.     /// <summary>    
    4.     /// The main entry point for the application.    
    5.     /// </summary>    
    6.     public static void Main()    
    7.     {    
    8.         ServiceBase.Run(new CalculatorWindowsService());    
    9.     }    
    10.   
    11. }    
  8. Right click on the App.config file - Edit WCF configuration, then a configuration window will open. Configure App.config file by defining service name, baseAddress, binding, contract, etc. like the following:
    1. <?xml version="1.0" encoding="utf-8" ?>    
    2. <configuration>    
    3.   <system.serviceModel>    
    4.     <services>    
    5.       <!-- This section is optional with the new configuration model    
    6.            introduced in .NET Framework 4. -->    
    7.       <service name="Services.CalculatorService"    
    8.                behaviorConfiguration="CalculatorServiceBehavior">    
    9.         <host>    
    10.           <baseAddresses>    
    11.             <add baseAddress="http://localhost:8000/ServiceModelSamples/service"/>    
    12.           </baseAddresses>    
    13.         </host>    
    14.         <!-- this endpoint is exposed at the base address provided by host: http://localhost:8000/ServiceModelSamples/service  -->    
    15.         <endpoint address=""    
    16.                   binding="wsHttpBinding"    
    17.                   contract="Services.ICalculator" />    
    18.         <!-- the mex endpoint is exposed at http://localhost:8000/ServiceModelSamples/service/mex -->    
    19.         <endpoint address="mex"    
    20.                   binding="mexHttpBinding"    
    21.                   contract="IMetadataExchange" />    
    22.       </service>    
    23.     </services>    
    24.     <behaviors>    
    25.       <serviceBehaviors>    
    26.         <behavior name="CalculatorServiceBehavior">    
    27.           <serviceMetadata httpGetEnabled="true"/>    
    28.           <serviceDebug includeExceptionDetailInFaults="False"/>    
    29.         </behavior>    
    30.       </serviceBehaviors>    
    31.     </behaviors>    
    32.   </system.serviceModel>    
    33. </configuration>  
  9. Rebuild the project.

  10. Open VS 2013 Developer Command Prompt, Run as administrator and navigate the path till bin like the following:

    cd /d F:\Tutorials\C#\Wcf_Test\CalculatorWindowsService\bin\Debug

  11. Now run the following command:

    WCF_Test>installutil.exe CalculatorWindowsService.exe

    It will install and host the WCF Windows Service. You can start it with the following steps:

    1. Search - Services.mst: There you will find “WCFWindowsServiceSample” as mentioned in the installer.
    2. Right click on it and Start the service.

      Now, Window service has been installed and hosted.

Step 3: Consume WCF Service to Client Side.

Client can consume services of hosted windows services in the form of APIs.

The following are the steps to consume APIs:

  1. Right click on Solution explorer - Add New Console project.

  2. Give the name of console project to “CalculatorClient”.

  3. Now, generate proxy file of service by the following steps:

    1. Open URL http://localhost:8000/ServiceModelSamples/service in the browser. Make sure windows service should be running.

    2. It will open the service details.

    3. Click on the URL : http://localhost:8000/ServiceModelSamples/service?wsdl

    4. You will get .wsdl file in the form of XML format.

    5. Save this file

    6. Open VS 2013 Developer Command prompt.

    7. Navigate till the folder of saved XML file and run the following command:

      F:\Tutorials\WCF_Test>svcutil.exe service.xml

    8. It will generate proxy file like “CalculatorService”. Add it to this project.

    9. Add reference “System.ServiceModel”.

    10. Add one App.Config file and configure like the following:
      1. <configuration>    
      2.   <system.serviceModel>    
      3.     <bindings>    
      4.       <basicHttpBinding>    
      5.         <binding name="BasicHttpBinding_ICustomerService" closeTimeout="00:01:00"    
      6.             openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"    
      7.             allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"    
      8.             maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"    
      9.             messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"    
      10.             useDefaultWebProxy="true">    
      11.           <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"    
      12.               maxBytesPerRead="4096" maxNameTableCharCount="16384" />    
      13.           <security mode="None">    
      14.             <transport clientCredentialType="None" proxyCredentialType="None"    
      15.                 realm="" />    
      16.             <message clientCredentialType="UserName" algorithmSuite="Default" />    
      17.           </security>    
      18.         </binding>    
      19.       </basicHttpBinding>    
      20.     </bindings>    
      21.     <client>    
      22.       <endpoint address="http://localhost:8000/ServiceModelSamples/service" binding="wsHttpBinding"    
      23.           contract="ICalculator"/>    
      24.     </client>    
      25.   </system.serviceModel>    
      26. </configuration>    
    11. Rebuild the project.

    12. Now go to Class file “Program” and call the service API’s method like the following:
      1. static void Main(string[] args)    
      2. {    
      3.     CalculatorClient calculator = new CalculatorClient();    
      4.     var addResult = calculator.Add(2, 4);    
      5.     Console.WriteLine("Sum: {0}", addResult);    
      6.     var result = calculator.Subtract(4, 2);    
      7.     Console.WriteLine("Subtract: {0}", result);    
      8.     Console.ReadKey();    
      9. }  

Folder structure is like the following:

wcf-windows-hosting

See the attached code.