Finding the Service Instance

How do I get access to the service instance from inside of a service operation?

Assuming that you're executing somewhere that a service operation is meaningful, you'll have access to the service operation context OperationContext.Current. From the service operation context you can get the service instance context and from the instance context you can ask it to GetServiceInstance.

How does the context know how to give you a service instance?

Early on in the execution of the operation, the service operation context was created. Shortly thereafter, a service instance context was created or one was reused if we happened to have it lying around and the service instance context was attached to the service operation context. The service instance context had attached to it an IInstanceProvider, which is the extensibility point for managing instances. There are a variety of instance providers for different uses that come with the system. An instance provider is able to cough up an instance based on a service instance context and optionally the message that is being processed.

Next time: Building with Encoders