Dusty
Dusty

Reputation: 2189

Can I host a WCF Service in a windows service?

I created a WCF project by going to Add New Project -> WCF service library and when I run it on the development environment, it opens up the WCF test client. How do I install this service on a server that doesn't have Visual Studio installed (I'd like to not host it on IIS). Should I write a new windows service?

Upvotes: 2

Views: 1684

Answers (3)

Justin Skiles
Justin Skiles

Reputation: 9523

Create a Windows Service project.

Add your WCF Service to this project.

In the main Windows Service class (defaults to Service1.cs), add a member:

internal static ServiceHost myServiceHost = null;

Modify OnStart() to start a new ServiceHost with your WCF Service type:

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

        myServiceHost = new ServiceHost(typeof(MyService));
        myServiceHost.Open();
    }

Modify OnStop():

protected override void OnStop()
    {
        if (myServiceHost != null)
        {
            myServiceHost.Close();
            myServiceHost = null;
        }
    }

Add a Setup and Deployment project (Setup Project) to your solution. Set output of that project to be the main output of the Windows Service project. When you build the Setup and Deployment project, you should see a Setup.exe file that you can use to install the service.

Keep in mind you still need to setup your endpoints and bindings. Look into using nettcpbinding for this setup.

As a final note, reference: Error 5 : Access Denied when starting windows service if you are experiencing problems when starting the Windows Service after installation.

Upvotes: 5

Antony Scott
Antony Scott

Reputation: 21996

Take a look at the TopShelf library. I've used it to create a number of WCF services.

TIP: If you're planning on writing more WCF services it might be worth your while reading up on port sharing.

Upvotes: 0

Aliostad
Aliostad

Reputation: 81700

You need to create a windows service project and then add reference to your WCF service and host it. In order to install the service, you do not need visual studio, you need to use installutil.exe.

Have a look here.

Upvotes: 0

Related Questions