Providing custom context to your WCF service operations

First off, I’d like to say that I absolutely love how extensible WCF is. So far there hasn’t been anything I can’t do. Unfortunately the documentation, examples and guidance around extensibility is still lacking a bit at this point. This is somewhat disturbing considering that RC1 just went out.

Now, on to what I really want to talk about here: providing custom context to your service implementations. We have an in house framework here at Mimeo, called our system framework, that provides some context much like System.Web’s HttpContext or even System.ServiceModel’s OperationContext. This in house framework exposes the current instance via a Current property (again, just like HttpContext::Current and OperationContext::Current). How and when the “current instance” is constructed is completely configurable via a factory method (provided via a delegate) that can be implemented per hosting environment. Built in factory method implementations include per-thread and per-appdomain, but in an environment like ASP.NET we actually maintain the lifetime in paralell with HttpContext::Current by storing it in the HttpContext::Items collection. Similarly we want the lifetime of this framework context to be tied to the call context of a WCF operation.

I took a couple diff. approaches while figuring out the best way to accomplish this in the world of WCF extensibility. Ultimately I fell into using a custom IServiceBehavior implementation, applied as an attribute, which extends the operations by hooking up a custom ICallContextInitializer. This approach allowed me to do some initialization right before a service operation is invoked and, when invocation completed, do some clean up. For more details on exactly what setup is required and what the order of execution is, check out this thread over on the WCF MSDN forums.

One thought on “Providing custom context to your WCF service operations

Leave a Reply