Reader Level:
ARTICLE

Hosting WCF Service With NetTcpBinding in Windows Service

Posted by Dhananjay Kumar Articles | WCF with C# June 18, 2010
This article will explain How to create a WCF service with netTcpBinding, How to host the WCF service in Windows service ,How to start windows service and How to consume the service.
  • 0
  • 0
  • 32244
Download Files:
 

Objective

This article will explain

  1. How to create a WCF service with netTcpBinding ?
  2. How to host the WCF service in Windows service ?
  3. How to start windows service ?
  4. How to consume the service ?
You can see video of this article Here

Create WCF Service

Step 1

Create a WCF Library project.

image1.gif

Step 2

Create Contract. Delete all the default code generated by WCF for you. And create a contract as below,

image2.gifimage2.gif
Step 3

Implement the Service

image3.gif

Step 4

Configure End Point for the service on netTcp Binding.
  1. Configure Service Behavior

  2. image4.gif
     
  3. Configure end point with netTcpBinding

    image5.gif
     
  4. Configure the meta data exchange end point

    image6.gif
Note: Make sure, you are providing name of the endpoints. Else you will catch up with run time exception while adding the service at client side

Full App.Config of WCF library project will look like

App.Config

<?xmlversion="1.0"encoding="utf-8" ?>
<configuration>
<
system.web>
<
compilationdebug="true" />
</system.web>
<
system.serviceModel>
<
services>
<
servicename="NetTcpServicetoHostinWindowsServices.Service1"behaviorConfiguration ="MyBehavior">
<host>
<
baseAddresses>
<
addbaseAddress = "net.tcp://localhost:9999/Service1/" />
</baseAddresses>
</
host>
<
endpointname ="NetTcpEndPoint"
address =""
binding="netTcpBinding"
contract="NetTcpServicetoHostinWindowsServices.IService1">
</endpoint>
<
endpointname ="NetTcpMetadataPoint"
address="mex"
binding="mexTcpBinding"
contract="IMetadataExchange"/>
</service>
</
services>
<
behaviors>
<
serviceBehaviors>
<
behaviorname ="MyBehavior">
<serviceMetadatahttpGetEnabled="False"/>
<serviceDebugincludeExceptionDetailInFaults="False" />
</behavior>
</
serviceBehaviors>
</
behaviors>
</
system.serviceModel>
</
configuration>

Create Windows Service

Step 1

Right click and add a new project in same solution. Choose the project type Windows Services from windows tab.

image7.gif

Step 2

Right click on Windows service project and add reference of

  1. System.ServiceModel

  2. Project reference of WCF Library project created in previous step

    image8.gif

    image9.gif
Step 3

Copy App.Config from WCF Service Library project and paste in Windows service project. To do so right click on App.config in WCF Library project and select copy then right click on Windows Service project and click on paste.

image10.gif
image11.gif

After copy and paste of APP.Config , we can see App.Config file in Windows Service Project also.

image12.gif

Step 4

Add Service Installer. To do so right click on Service1.cs in windows service project and click on view designer.
 
image13.gif

Once designer page is open, right click on designer page and click on add installer

image14.gif

Once we will right click on design surface of Service.cs file and click add Installer, it will add ProjectInstaller.cs file.

image15.gif

Right click on the ProjectInstaller.cs file and select view designer.

image16.gif

 On designer page, we can see there is ServiceProcessInstaller1 and serviceInstaller1 is there.

Right click on ServiceProcessInstaller1and select properties. In properties set the Accountattribute to NetworkServices

image17.gif

 Right click on ServiceInstaller1and select properties. In properties set the Start Type attribute to Automatic

image18.gif

Step 5


Modify Window service to host the WCF service. To do, open Service1.cs file in Windows service project.
  1. Add the below name spaces

  2. image19.gif
     
  3. Declare a variable

    image21.gif
     
  4. On Start method of Window service

    image20.gif
     
  5. On Stop method of Window service
    image21.gif
     
  6. On the event of back ground worker 

    image22.gif

So full source code of Service1.cs in windows service project will be like below,

Service1.cs

using System;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Diagnostics;
usingSystem.Linq;
usingSystem.ServiceProcess;
usingSystem.Text;
usingSystem.ServiceModel;
usingNetTcpServicetoHostinWindowsServices;

namespaceHostingWindowsService
{
publicpartialclassService1 : ServiceBase
    {
internalstaticServiceHostmyHost = null;
BackgroundWorker worker;
public Service1()
        {
InitializeComponent();
        }

protectedoverridevoidOnStart(string[] args)
        {
 
worker = newBackgroundWorker();
worker.DoWork += newDoWorkEventHandler(worker_DoWork);

        }
voidworker_DoWork(object sender, DoWorkEventArgs e)
        {

if (myHost != null)
            {
myHost.Close();
            }

myHost = newServiceHost(typeof(NetTcpServicetoHostinWindowsServices.Service1));
myHost.Open();

        }

protectedoverridevoidOnStop()
        {

if (myHost != null)
            {
myHost.Close();
myHost = null;
            }
 
        }
    }
}

Step 6

Build the solution. After successful built of solution, you can see exe file in debug folder of bin folder. After building the solution, right click on solution and select open folder in Windows Explorer. Once folder is open Windows service project folder. Inside that open bin folder.Inside that open Debug folder. Inside Debug folder you should able to see windows service exe file.

image24.gif

Click on the address bar of the folder and copy the full path of this exe file.

Step 7

Install the windows service.

  1. First search what is the path of InstallUtil in your machine. To search this path , click on start and open find and if you are using Windows 7 then browse to your C drive and type InstallUtil , in top right corner search text box.
  2.  
  3. Once you get the full path of InstallUtil ,Open your command prompt ad change directory to full path of InstallUtil.
     
  4. Now just type InstallUtil.exe and press enter, you will get help details on how to use InstallUtil.exe.
     
  5. Now to install window service we created, type the below command on your command prompt. Make sure you are giving correct and full path of window service exe.

    image25.gif
     
  6. After successful installation, you will get below message.

    image26.gif

     
  7. Click on Start and type run and in run window type Service.msc

    image27.gif
It will open all the services. We can see Service1 is listed there. If you remember Service1 is name of the service class in Windows service project.

image28.gif


This service is automatic started. Right click on the service and click on the Start.

Now our WCF Service is up and hosted in Windows Services.

Step 8

Create the client.
  1. To create the client right click on solution and add a new project of type Console application.

  2. Right click on the console application and add service reference. Copy base address from App.config of windows services and paste it here.

    image29.gif
     
  3. Now simply create the instance of Service1Client and call the service
Programs.cs

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
using ConsoleClient.ServiceReference1;

namespaceConsoleClient
{
classProgram
    {
staticvoid Main(string[] args)
        {
Service1Client proxy = newService1Client();
Console.WriteLine(proxy.GetData(9));
Console.Read();
        }
    }
}


Press F5 to run the console application. Make sure client console application is set as startup project.

image30.gif

So it was all about, how to create a WCF Service with netTcpBinding and host in windows service. I hope this post was useful. Thanks for reading. Happy Coding

COMMENT USING