Daniel
Daniel

Reputation: 1481

WCF Service hosted in a Windows Service - Which one should do all the work?

I'm writing my first WCF service but I'm a little unsure of where the service' main function should be implemented.

The main purpose of my service is to perform tasks on a schedule and eventually log its status back to a remote server. The idea of the WCF service is to allow communication between a system tray application and the service. My question is where should I implement the task scheduling and database logging?

Should: A) the Windows service only host the WCF service and do nothing else, leaving the WCF service to do all of the work and communication.

B) the Windows service host the WCF service and do all of the work, leaving the WCF service to do communication and nothing else.

In the case of B, how does the Windows service get data to and from the WCF service? The ServiceHost doesn't appear to provide access to the methods of the WCF service. So would I need to create a new client instance and connect to the WCF service the same way I would in the system tray application? Is it possible to have more than one simultaneous connection? (I'm using net.tcp, mainly because the tutorial I followed was using it.) There is also a possibility that I may want the server application to connect to the client's WCF service later.

Upvotes: 1

Views: 179

Answers (1)

lesscode
lesscode

Reputation: 6361

A service doesn't have a "main function" like a program would - it offers a service contract (interface) containing operations that can be invoked by service clients. WCF allows that contract to be exposed to callers that may be running in separate processes or on separate machines.

Once you have a WCF service implementation, you can host it in many different ways. One way is inside a Windows Service process. To do this, you would typically create a System.ServiceModel.ServiceHost containing your service type (or instance) and Open() it.

The Windows Service doesn't communicate with the WCF service instance beyond that initial creation - the service host will handle any calls in to the endpoint specified by the address and binding, and dispatch them to your service instance.

So, your "A" option is closest to what you want.

Your tray application will be the service client, and will invoke operations by sending messages to the service (whose ServiceHost will be listening for them).

For handling multiple simultaneous operations, you'll need to become familiar with System.ServiceModel.ConcurrencyMode.

Note that in your scenario, if you're not expecting to be invoking the service from another machine, you might want to consider a named pipe binding rather than a TCP binding.

Upvotes: 1

Related Questions