Friday, 6 March 2015

Working with CallContext in WCF

The CallContext class is provided by the .NET Framework to "track" the logical execution of a request. It is sort of a property bag that is carried through the execution path.

Why CallContext is quite useful in WCF?

Prior to .NET 4 (most specifically async-await) paradigm, WCF methods were sort of synchronous. I use "synchronous" is a very loose terms to suggest that no explicit Threads were created by the developer to process a request.

However with the introduction of async-await pattern and Task Parallel Library (TPL), developing asynchonous code has become quite easy.

The issue really is that WCF was never designed (or at least visioned) to handle async-await in a graceful manner. Normally WCF use OperationContext to store extensions that can be used later in the application. The OperationContext hold state in thread local store which will never play happy with async-await. There are dozens of questions in StackOverflow around this matter.

There are few ways to design a WCF service that leverage the power of async-await.

  • We can discount OperationContext completely and pass the any data items around.
  • We can store the data points in a backing store and read when required. We may need to pass around a references, this may be acceptable. 
  • We could consider CallContext to store request specific information and read it whenever required. 
The data stored in CallContext is maintained across threads (as by definition CallContext is per logical execution context). In theory CallContext could be considered as a replacement to OperationContext. We can continue using async-await without having to worry about the limitations in the framework (in this case WCF). 

Example

The following code is a simple wrapper over the CallContext.



A word of caution about what you should store.

  • Generally it is advised that you should only consider storing immutable objects in CallContext. There is an excellent post here that explains the pros and cons.


An operation can use the CallContext wrapper in this fashion.

Summary

There is no double that CallContext is a very strong candidate for maintaining per-request data in WCF. Here is another post around CallContext from Winterllect. However there is a twist of CallContext that we need to be very careful about. I will write up my findings in the next post.  





1 comment: