Intercepting Client Calls
To intercept client-side calls WCF provides the interface IClientMessageInspector, defined as:
public interface IClientMessageInspector
{
object BeforeSendRequest(ref Message request,IClientChannel channel);
void AfterReceiveReply(ref Message reply,object correlationState);
}The BeforeSendRequest( ) method is called just before
the message is sent down the wire, allowing you to affect the request message. Similarly,
the AfterReceiveReply( ) method is your chance to
interact with the reply message for post-call processing.
The client runtime represented by the ClientRuntime
class contains a collection of message inspectors:
public sealed class ClientRuntime
{
public SynchronizedCollection<IClientMessageInspector> MessageInspectors
{get;}
//More members
}You can add your message inspector to the collection by associating the proxy with an
endpoint behavior. That behavior needs to add the inspector in the ApplyClientBehavior( ) method:
public interface IEndpointBehavior
{
void ApplyClientBehavior(ServiceEndpoint endpoint,ClientRuntime clientRuntime);
//More members
}To encapsulate these steps I wrote the class InterceptorClientBase<T> defined in Example E-4.
Example E-4. The InterceptorClientBase<T> class
public abstract class InterceptorClientBase<T> : ClientBase<T> where T : class { public InterceptorClientBase( ) { Endpoint.Behaviors.Add(new ClientInterceptor(this)); } public InterceptorClientBase(string endpointName) : base(endpointName) { Endpoint.Behaviors.Add(new ...