Sunday, January 31, 2010

Inspecting Parameters passed to an Operation through IParameterInspector

Windows Communication Foundation has a very extensible and loosely coupled architecture. Recently I was trying to do some input validations on the parameters that were passed to the WCF Service.

IParameterInsepctor is the interface you need to implement. Before I explain the code, just want to give a overview of extension points in WCF. I came across a very nice article, which explains all the extension points.

On the server side when the message is received by the WCF runtime, it goes through different channels before the operationCode is executed. The main extensibility points here are
1) MessageInspection -- You can get the Xml representation of the message here, you can SIGN the messages, Log it, Validate it against a schema.
2) OperationSelector -- You can do some kind of Caching etc
3) MessageFormatting -- Here you can do some customFormatting of the message.
4) Parameter Inspection -- Here you can do Input parameter validation etc. Bascially you get access to the paramaters passed by the client to your operation.

 All you have to do it
  a) Implement the IParameterInspector


b) Implement a class which derives from Attribute and implements IOperationBehaviour interface. Bascially you have to add the CustomBehaviour to the Runtime. So when runtime tries to call the operation it will first go through the Custom Behaviour.

c)Add this attribute on the Operation.

d) If you want to add the behaviour through config then you need to implement a class which derives from BehaviorExtensionElement.

WCF runtime uses reflection to find the behaviours, after that it checks the Config file for any custom behaviours.

You can download the SourceCode Here.