You may find the need to determine the request and reply message size when calling a service operation.
It can be for logging purposes, or a practical one such as deciding whether you need to compress the data or not.
The key component in WCF that knows about the actual size of the message is the message encoder, and of course, you can plug-in your own encoder as part of WCF’s extensibility point. Ahhh, got to love this framework!
Lets examine the feature requirements first –
- We need to have a way to get the incoming message size in our service implementation.
- We need a way to enable the client to get the reply message size.
You can download the code here.
Basically, in order to implement a message encoder and to plug it in, you need to implement your own MessageEncoder, MessageEncoderFactory, and MessageEncodingBindingElement.
Additionally, since this is part of the binding elements, we need to plug it in as part of the binding.
The implementation is fairly simple, since all I did was wrap the existing ones and added my message headers in the proper place.
I will not show this code here, it’s pretty straight forward, I recommend you just download the code and take a look at it.
Finally, I implemented a behavior that you can attach to your service which does all the heavy lifting for you.
It actually switches the current binding with a wrapper binding that plugs in our custom message encoder, pretty sweet.
In conclusion, here’s how our service would look like:
As you can see the usage is very simple.
You define the behavior on your service, then you can access the extension to retrieve the size of the incoming request and do whatever you want with it.
One more tip – Keep the meta-data aligned:
I thought I should share a problem I experienced when I coded this – everything looked fine and it all worked.
However, when a developer tried to add a service reference against the service meta-data, he would get an incorrect binding.
I was wondering why it happened, my wrappers were delegating every single operation to the existing ones, so what was I missing?
Ahhhh.. Of course! Don’t forget about the ‘IWsdlExportExtension’ and ‘IPolicyExportExtension.
Encoding binding elements could be implementing those interfaces to participate in the building of the service meta-data.
I fixed the problem by implementing these interfaces myself and forward it to the existing binding element if it too has implemented it.