How to Debug a WCF Service Hosted in Windows Service

This article shows how we can debug a WCF Service in Visual Studio which is hosted in a Windows Service with netTcpBinding.
 
As we know when we create a WCF Service as a class library in Visual Studio and run the service, we don't need a host (like Self-Hosting App, Windows Services, IIS or WAS). Right? It happens because fortunately Microsoft has already included a small testing service host and a test client in order to ease development and testing of WCF services. Press F5 in Visual Studio and you are set to start debugging by setting a breakpoint anywhere in the service where we want to. You would see the following message when the WCF Service runs:
 
WCF.jpg 
 
But suppose we host our WCF service in a Windows Service and make the Windows Service as our main start up project, then it becomes difficult to debug our WCF Service because then the Windows Service is the main driving application (host) which doesn't allow running the WCF Service by a debugger.
 
It gives the following error message if you try to do that:
 
Error-Mesage-in-WCF.jpg 
 
So what is the solution?  For this problem, we have the following simple remedial options:
  1. Through Visual Studio: In this option (which I am not going to discuss here), you need to open your Visual Studio in administrative mode and you have to have your Service attached to the process. For more details of that, see the MSDN article:
    http://msdn.microsoft.com/en-us/library/c6wf8e4z.aspx
  2. Through Code: We are going to discuss this option in detail in this article.
To explain this, I divided this article into the following sections:
  1. Creating a small WCF Service with netTcpBinding
  2. Creating Windows Service Host
  3. Setting a Windows Service that enables debugging in Visual Studio
  4. Creating our own Test Client

1. Creating a small WCF Service with netTcpBinding

  • On the File menu, point to New and then click Project.
  • In the New Project dialog box, expand the Visual C# node and click WCF, followed by WCF Service Library. Click OK to open the project.
  • A builtin WCF Service with two operation contracts (by default) is created for you by Visual Studio. You don't need to change any operation contract or data contract because here our focus is not to learn how to create a WCF Service and their contracts (operation/Data).
  • For netTcpBinding, we need to change the contents of the default app.Config file as:
    1. <configuration>  
    2.   <system.serviceModel>  
    3.     <services>  
    4.       <service name="MyWcfService.Service1">  
    5.         <endpoint address="" binding="netTcpBinding" bindingConfiguration=""  
    6.           contract="MyWcfService.IService1">  
    7.           <identity>  
    8.             <dns value="localhost" />  
    9.           </identity>  
    10.         </endpoint>  
    11.         <endpoint address="mex" binding="mexTcpBinding" bindingConfiguration=""  
    12.           contract="IMetadataExchange" />  
    13.         <host>  
    14.           <baseAddresses>  
    15.             <add baseAddress="net.tcp://localhost:8732/Design_Time_Addresses/MyWcfService/Service1/" />  
    16.           </baseAddresses>  
    17.         </host>  
    18.       </service>  
    19.     </services>  
    20.     <behaviors>  
    21.       <serviceBehaviors>  
    22.         <behavior>  
    23.           <!-- To avoid disclosing metadata information,   
    24.           set the value below to false and remove the metadata endpoint above before deployment -->  
    25.           <serviceMetadata/>  
    26.           <!-- To receive exception details in faults for debugging purposes,   
    27.           set the value below to true.  Set to false before deployment   
    28.           to avoid disclosing exception information -->  
    29.           <serviceDebug includeExceptionDetailInFaults="True" />  
    30.         </behavior>  
    31.       </serviceBehaviors>  
    32.     </behaviors>  
    33.   </system.serviceModel>  
    34. </configuration>
  • That's it! We are done with creating our Test WCF Service.

2. Creating a Windows Service Host

 
Now we create a Windows Service project in Visual Studio:
  1. On the File menu, point to New and then click Project.
  2. In the New Project dialog box, expand the Windows node and click Window Service and Click OK to open the project.
  3. A default Window service project is created.
  4. Although this step is optional right now, eventually we would end up doing this because we want to install our Windows Service into the system. For this, we need to add a project installer into our windows service so that we can install our windows service using the "regsvr32" command. In order to do that, we go to the designer of Service1.cs and:
    • Right-click in the designer of Service1.cs. Choose the "Add Installer" option from the menu.
    • Visual Studio automatically creates a ProjectInstallar for us.
    • Give any name to your service in the properties window of serviceInstaller1.
    • For how we can install any windows service using the "installutil" command, we could go to the following MSDN link:
      http://msdn.microsoft.com/en-us/library/sd8zc8ha%28v=vs.80%29.aspx
       
  5. Add the WCF Service DLL reference into the Window Service project.
  6. Add a System.ServiceModel reference to the Windows Service
  7. Open the Service1.cs file and create WCF Service host into the OnStart() method as follows:
    1. public partial class Service1 : ServiceBase  
    2. {  
    3.     ServiceHost host;  
    4.     public Service1()  
    5.     {  
    6.         InitializeComponent();  
    7.     }  
    8.     protected override void OnStart(string[] args)  
    9.     {  
    10.         Type serviceType = typeof(MyWcfService.Service1);  
    11.         host = new ServiceHost(serviceType);  
    12.         host.Open();  
    13.     }  
    14.     protected override void OnStop()  
    15.     {  
    16.         host.Close();  
    17.     }  
    18. }
  8. Add a new "app.config" file into the Windows Service Project.
  9. Copy the same contents of the WCF service app.config (described in section1.4) into our newly added Windows Service app.config file.

3. Setting Windows Service that enables debugging in Visual Studio

 
Open the Program.cs file of the Windows Service Host Application and replace the existing Program.cs with the following code:
  • In the following code, we created an instance of the "Service1" class of the Windows Service and explicitly called our own methods: OnDebugMode_Start() and OnDebugMode_Stop().
  • This portion will be run only in DEBUG Mode since we used the #if DEBUG directive.
  • The portion in the #else block will not be run in DEBUG Mode.
  • We also put the Main Thread into an infinite time Sleep Mode in order to make "Debugging" available continuously until we want.
Window-Service-Host-in-WCF.jpg 
 
Note: When we want to install this Windows service using the "installutil" command, we have to comment out the #if DEBUG directive and its code as in the following:
  1. static void Main()  
  2. {  
  3.  System.Threading.Thread.CurrentThread.Name = "ServiceMain";  
  4.  try  
  5.  {  
  6.   //#if DEBUG  
  7.   //// Run as interactive exe in debug mode to allow easy debugging.   
  8.   //var service = new Service1();  
  9.   //service.OnDebugMode_Start();  
  10.   //// Sleep the main thread indefinitely while the service code runs in OnStart()   
  11.   //System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);  
  12.   //service.OnDebugMode_Stop();  
  13.   //#else  
  14.   ServiceBase[] ServicesToRun;  
  15.   ServicesToRun = new ServiceBase[]  
  16.   {  
  17.    new Service1()  
  18.   };  
  19.   ServiceBase.Run(ServicesToRun);  
  20.   //#endif  
  21.  } catch (Exception exc)  
  22.  {  
  23.   throw exc;  
  24.  }  
  25. }
Open the Service1.cs file and add two more public methods in the same class, which basically calls the OnStart() and OnStop() methods internally:
  1. public void OnDebugMode_Start()   
  2. {  
  3.  OnStart(null);  
  4. }  
  5. public void OnDebugMode_Stop()   
  6. {  
  7.  OnStop();  
  8. }  
Press F5 to run the service and make sure the service is running properly. Since the Windows Service is in debugger mode, it won't complain as in Figure 2.
 

4. Creating our own Test Client

  1. Create any WinForm Application or Console Application to be a client of our WCF Service which will consume the WCF Service.
  2. Make sure WCF Service is running.
  3. Right-click the Reference tab of your project. Click "Add a ServiceReference".
  4. The Add Service Reference Window will open
  5. Put the WCF Endpoint base address (copying from app.config) into the Address bar of the Window.
  6. Click Go. It must have found out our WCF Service interfaces.
  7. Click OK. In this way, you added a service reference to you client project.
  8. Create a Proxy Client Object of your WCF Service as:
    1. ServiceReference1.Service1Client objectProxyClient = new Service1Client(); 
  9. Access interfaces of the WCF Service with an "objectProxyClient" object.
So, here we learned how to easily debug a WCF Service in Visual Studio which is hosted in a Window Service by making a small Test WCF Service with netTcpBinding, hosting a Windows Service and Test Client Tool.


Similar Articles