There’s no easy way to describe the division of responsibilities between layers of the framework in a WCF service. Although we encourage a particular structure for handling messages, we don’t have enforcement to back that up. I’ll talk for a few days about a four-layer model consisting of a hosting layer, a service layer, a channel layer, and a transport layer. These layers are both subdividable and collapsible. For example, you can partition the transport layer as finely as you like by dividing the responsibilities of that layer among any number of nested components. Likewise, you can collapse the service layer by directly reading untyped messages from the channel and performing your own dispatching. If you want to do such things, then you’ll have to adjust the following description to your monstrous creation.
The hosting layer contains whatever magic necessary to get your service launched and running. Inside the service, you typically don’t care at all how the service got started. That doesn’t mean that you can pair any hosting environment and service together though. A service imposes requirements for activation and state management on the hosting environment. The service must start no later than the first message destined for the service. The service state must end no sooner than the last message using that state.
IIS 6 can listen for HTTP traffic and use the arrival of a message to start running a service. By carefully configuring the hosting environment, you can create a service that starts just in time to receive its first message. When the service stops running, IIS will start a new copy the next time it receives a message destined for that service. This method works fine when your service speaks HTTP and keeps no state around between messages.
If the service gets its first message over a named pipe, then this method wouldn’t work. IIS will not be listening on the named pipe when the message arrives and so the service will never start. By putting your web service inside of an NT service instead, you would sidestep the problem of activating on the first message. An NT service starts immediately before any messages arrive. Your web service can listen for the first message using any mechanism it wants.
If the service needs to hold any state between invocations, then the method of directly hosting in IIS also wouldn’t work. There’s no guarantee that you’re talking to the same service instance from moment to moment because IIS can decide to stop the service and later start a new copy. The hosting environment needs to expand to include some form of durable storage. Find somewhere else to store that data, such as in ASP.NET session state.
We’ll now put aside the problem of process management and instead look at the problem of defining what the service does.
Next time: Pieces of the Messaging Framework, Part 2