Sunday, February 06, 2011

How to Intercept a WCF Message to track message size

As we are building out our mobile WCF endpoints we want to be able to track/trend the size of messages which are being sent to our phones.  We want to do this for multiple reasons 1) to trend our message sizes over time to make sure we are being good little developers 2) to be able to report and measure the amount of data we are sending to each of our mobile devices because bandwidth is not free.
I will say that my approach may just be ‘one way’ to accomplish this, but it works for me.
In order to accomplish task we will be extending WCF in multiple places and creating multiple files.  I will list out a quick list of the files then dive into each file a bit further.  In the end we will have a working solution which will be good enough to get you started.

WCF Extension points

CustomServiceHost => This extends ServiceHost
CustomServiceHostFactory => This extends ServiceHostFactory
MessageDiagnosticsInterceptor => This implements the IDispatchMessageInspector interface (used to grab the outbound message)
MessageDiagnosticsServiceBehavior => This implements the IServiceBehavior interface (used to setup the interceptor)

The way this will work is this.  We will need to create each of our 4 custom classes, but the glue that binds this all together is how we setup our endpoint to use the CustomServiceHostFactory.

Creating our Custom Service Host

public class CustomServiceHost : ServiceHost
{
   public CustomServiceHost()
   {
   }
   public CustomServiceHost( Type serviceType, params Uri[] baseAddresses )
       : base( serviceType, baseAddresses )
   {
   }
   protected override void OnOpening()
   {
       Description.Behaviors.Add( new MessageDiagnosticsServiceBehavior() );
         
       base.OnOpening();
   }
}

In the above code the only real important thing to notice is that we are adding a behavior during the OnOpening call.  We will define this behavior below.

Creating our Custom Service Host Factory

public class CustomServiceHostFactory : ServiceHostFactory
{
   protected override ServiceHost CreateServiceHost( Type serviceType, Uri[] baseAddresses )
   {
       return new CustomServiceHost( serviceType, baseAddresses );
   }
}

Read more:  devlicio.us