May 6, 2011

Have WCF Service hosted on windows service.

This one is quite old, anyway, as I am using my blog for adding notes to myself as well, I will repeat the solution so I can later find it :).

Maybe you will find it useful as well.

To host a WCF service on top of Windows service you need to do the following:

1. Create the windows service that will host the WCF Service.

2. In the windows service add references to the following assemblies:

2.1. System.ServiceModel

2.2. System.ServiceProcess.

3. Declare the following in the Service class:

ServiceHost host = null;

4. In the OnStart method of the service, instantiate the host variable and the WCF Service instance:

protected override void OnStart(string[] args)
{
    if (host != null)
    {
        host.Close();
    }


    SomeService.ServerAgent server = new SomeService.ServerAgent();
    host = new ServiceHost(server);
    host.Open();
}

5. We need to handle Service stop as well, add the following code to the OnStop method of the Windows Service:

protected override void OnStop()
{
    host.Close();
    host = null;
}

6. All we need to do now is to set some bindings / endpoints. NOTE: They should go to the app.config file of the WINDOWS service. Just copy them from the WCF Service web.config.

You are done.

Install and start the windows service and navigate to the Url Address you added as endpoint. You should be able to browse it.

No comments: