WCF/WF - passing parameter to WCF method from IDispatchMessageInspector

Asked By Mert on 27-Jan-11 04:12 AM

In IDispatchMessageInspector#AfterReceiveRequest() I'm allocating an  EFContext and I'm deallocating this context at IDispatchMessageInspector#BeforeSendReply method by passing the context object with correlationState. But I couldn't find a way to pass this object to the actual WCF method call which will use the context. Any ideas?
Indranil Chatterjee replied to Mert on 27-Jan-11 06:42 AM
Instead of using the state, try passing that using OperationContext.Current.Extensions. For that, you need to write an implementation of IExtension<OperationContext>. In that custom class (let's say MyContext) that implements IExtension<OperationContext>, you can create and store the EF context. In the AfterReceiveRequest method, you can create an instance of this class and add it to the extensions as:

OperationContext.Current.Extensions.Add(new MyContext()); //MyContext can hold an instance of EFContext internally
This can then be accessed in the service operation as:
var ctx = OperationContext.Current.Extensions.Find<MyContext>();

It can be removed in the BeforeSendReply method as:
var ctx = OperationContext.Current.Extensions.Find<MyContext>();

Here is a link that explains this: http://hyperthink.net/blog/a-simple-ish-approach-to-custom-context-in-wcf/
I hope this helps.
Mert replied to Indranil Chatterjee on 27-Jan-11 07:44 AM
thanks, that did the trick.