I recently came across a requirement to implement a Windows Communication Service that acts as a message router across several other WCF backend services. This router service main functionality is to encapsulate the backend services and also to add automatic request monitoring. This should not be hard I was thinking but there are couple of twists, first the router service should not sensitive to the services themselves and how they change and communicate with their clients. It also will be handing encrypted messages that it cannot decrypt as these messages belong to other partners that we do not control and of course do not have the certificate used for encryption.
The way this is done is by implementing custom WCF message dispatch inspector and custom WCF message client message inspector behaviours. Why do we need both as our service acts as a WCF to all the clients and as a client to all the backend services. So the main idea is to when a message is received over the wire the entire message body is escaped and placed in a custom header element and before this message is sent to the backend the original message body is extracted from the header and written back to the message sent. While the response is being received from the backend service the same logic happens but in the reverse order. So the reply is written to the custom header as an escaped string and then before this reply is delivered to the original caller the reply is read from the header and sent to the client. Simple right J well it will get even better; since we want the original message unparsed and not changed coming on the wire this has to be done using a custom message encoder for both ways, receiving requests from the clients and receiving responses from the backend services. So to try to make this simple I placed the following diagram.
So you need to implement a custom message encoder inheriting from the class “MessageEncoder” and mainly implement the method “ReadMessage” to be as follows.
So you need to implement first a custom class inheriting from “IDispatchMessageInspector” and it should first override the method “ApplyDispatchBehavior” to add this dispatch behavior to the endpoint as follows.
Then you need to implement the method “BeforeSendReply” to put the original reply back on the wire as follows.
You will then need to implement the method “BeforeSendRequest” from the class “IClientMessageInspector” to put the original request back on the wire before we send it to the backend services.
And that’s it J