Intercepting your WCF messages in Silverlight 2.0

In many applications you want to intercept WCF messages for doing stuff like, logging, tracing, passing a user context, language identifier, etc. Typically this can be done through the IClientMessageInspector that resides in the System.ServiceModel.Dispatcher. Unfortunately this interface doesn’t exist in Silverlight 2.0.

Thankfully WCF is very extensible, and there is a sample Silverlight Web Services Samples on MSDN Code Gallery that shows how you can still use the IClientMessageInspector by implementing a custom binding. You simple use the BasicHttpMessageInspectorBinding that receives in the constructor an instance of type IClientMessageInspector. For example:

BasicHttpMessageInspectorBinding binding = new BasicHttpMessageInspectorBinding(new TraceInspector());

Note that the sample only allows you to pass one inspector, if you need to pass several inspectors you can use the decorator pattern to pass multiple.

public class ClientMessageInspectorDecorator : IClientMessageInspector
{
    IClientMessageInspector[] inspectors;

    public ClientMessageInspectorDecorator(params IClientMessageInspector[] inspectors)
    {
        this.inspectors = inspectors;
    }

    public object BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        foreach (var item in inspectors)
        {
            item.BeforeSendRequest(ref request, channel);
        }

        return null;
    }

    public void AfterReceiveReply(ref Message reply, object correlationState)
    {
        foreach (var item in inspectors)
        {
            item.AfterReceiveReply(ref reply, correlationState);
        }
    }
}