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.

clip_image002[4]

Step 2

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

clip_image004[4]

Step 3

Implement the Service

clip_image006[4]

Step 4

Configure End Point for the service on netTcp Binding.

1. Configure Service Behavior

clip_image008[4]

2. Configure end point with netTcpBinding

clip_image010[4]

3. Configure the meta data exchange end point

clip_image011[4]

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

<?xml version=1.0 encoding=utf-8 ?>

<configuration>

<system.web>

<compilation debug="true" />

</system.web>

<system.serviceModel>

<services>

<service name="ServicetohostinWindow.Service1" behaviorConfiguration ="MyBeh">

<host>

<baseAddresses>

<add baseAddress = "net.tcp://localhost:9292/Service1/" />

</baseAddresses>

</host>

<endpoint name ="TcpEndPoint"

address =""

binding="netTcpBinding"

contract="ServicetohostinWindow.IService1">

</endpoint>

<endpoint name ="MetaDataTcpEndpoint"

address="mex"

binding="mexTcpBinding"

contract="IMetadataExchange"/>

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior name ="MyBeh">

<serviceMetadata httpGetEnabled="False"/>

<serviceDebug includeExceptionDetailInFaults="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.

clip_image013[4]

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

clip_image014[4]

clip_image015[4]

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.

clip_image016[4]

clip_image017[4]

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

clip_image018[4]

Step 4

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

clip_image019[4]

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

clip_image021[4]

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

clip_image022[4]

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

clip_image024[4]

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

Right click on ServiceProcessInstaller1 and select properties. In properties set the Account attribute to NetworkServices

clip_image025[4]

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

clip_image026[4]

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

clip_image028[4]

2. Declare a variable

clip_image029[4]

clip_image030[4]

3. On Start method of Window service

clip_image032[4]

4. On Stop method of Window service

clip_image033[4]

5. On the event of back ground worker

clip_image035[4]

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

Service1.cs

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.ServiceModel;

using ServicetohostinWindow;

namespace HostingWindowsService

{

public partial class Service1 : ServiceBase

{

internal static ServiceHost myHost = null;

BackgroundWorker worker;

public Service1()

{

InitializeComponent();

}

protected override void OnStart(string[] args)

{

worker = new BackgroundWorker();

worker.DoWork += new DoWorkEventHandler(worker_DoWork);

}

void worker_DoWork(object sender, DoWorkEventArgs e)

{

//throw new NotImplementedException();

if (myHost != null)

{

myHost.Close();

}

myHost = new ServiceHost(typeof(ServicetohostinWindow.Service1));

myHost.Open();

}

protected override void OnStop()

{

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.

clip_image037[4]

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. Once you get the full path of InstallUtil , Open your command prompt ad change directory to full path of InstallUtil.

3. Now just type InstallUtil.exe and press enter, you will get help details on how to use InstallUtil.exe.

4. 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.

clip_image039[4]

5. After successful installation, you will get below message.

clip_image041[4]

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

clip_image042[4]

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.

clip_image044[4]

clip_image046[4]

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.

clip_image047[4]

3. Now simply create the instance of Service1Client and call the service

Programs.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Client.ServiceReference1;

namespace Client

{

class Program

{

static void Main(string[] args)

{

Service1Client proxy = new Service1Client();

Console.WriteLine(proxy.GetData(9));

Console.Read();

}

}

}


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

clip_image049[4]

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

Advertisements

8 thoughts on “Hosting WCF Service with netTcpBinding in Windows Service

  1. Dear sir,
    You have done an excellent work, very easy and very detailed tutorial and honestly followed your great logic.
    I tested, its working fine from the source code, but i got a problem after creating the service and installing as windows service.
    while i am trying to use or trying to add a reference of the WCF service hosted by windows service, I am getting a TCP error 10061 (working fine if i am executing from source).
    I dont know how to check the real WCF service is running along with the windows service, but i am sure windows service is running.
    I am really struck with this situation, I am using it in a XP machine locally, i also added exception in firewall for port: 9999.

    kindly advice.
    i appreciate your time in this regard.

    thanks,
    Yashin

  2. Yashin,

    add Worker.RunWorkerAsync() in to Service1.cs

    ———————-

    Service1.cs

    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.ServiceModel;
    using ServicetohostinWindow;
    namespace HostingWindowsService
    {
    public partial class Service1 : ServiceBase
    {
    internal static ServiceHost myHost = null;
    BackgroundWorker worker;
    public Service1()
    {
    InitializeComponent();
    }
    protected override void OnStart(string[] args)
    {
    worker = new BackgroundWorker();
    worker.DoWork += new DoWorkEventHandler(worker_DoWork);

    /////////////////////////////////
    Worker.RunWorkerAsync();
    ////////////////////////////////

    }
    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
    //throw new NotImplementedException();
    if (myHost != null)
    {
    myHost.Close();
    }
    myHost = new ServiceHost(typeof(ServicetohostinWindow.Service1));
    myHost.Open();
    }
    protected override void OnStop()
    {
    if (myHost != null)
    {
    myHost.Close();
    myHost = null;
    }
    }
    }
    }

    Abdulraoof Arakkal

  3. Hi Abdul,

    Your post cleared all my confusions.It is really good for beginners.I did the same as you posted…I could see the result.Thers is clarity in each step. Thank you so much…

  4. Hi

    I am getting this error when adding reference to service and finding the service.

    Metadata contains a reference that cannot be resolved: ‘net.tcp://localhost:6050/Service1’.
    Could not connect to net.tcp://localhost:6050/Service1. The connection attempt lasted for a time span of 00:00:01.0312500. TCP error code 10061: No connection could be made because the target machine actively refused it 127.0.0.1:6050.
    No connection could be made because the target machine actively refused it 127.0.0.1:6050
    If the service is defined in the current solution, try building the solution and adding the service reference again.

    Any clue??

  5. Very useful and detailed article .Thanks for this article.

    But i have received the below error :

    System.ServiceModel.EndpointNotFoundException: Could not connect to net.tcp://localhost:8732/Service1/. The connection attempt lasted for a time span of 00:00:02.0531174. TCP error code 10061: No connection could be made because the target machine actively refused it 127.0.0.1:8732. —> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:8732
    at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
    at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
    at System.ServiceModel.Channels.SocketConnectionInitiator.Connect(Uri uri, TimeSpan timeout)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s