3

I wanted to know if it is wise to store and reference the OperationContext.Current object in a instance variable of a WCF service host instance. The service host is set to InstanceContextMode.PerCall so every new request gets its own instance.

The reason I ask this is becuase WCF does not guarantee thread affinity. On occasion WCF can start the request on one thread and end the request on a different thread.

The OperationContext.Current object is stored in Thread Local Storage. When a new thread is used for the same operation, WCF "propagates" to the new thread.

In this event, when WCF starts using a thread different, is it still safe to access the OperationContext object that was stored in the instance variable of my service instance?

Mohammed Ali
  • 1,027
  • 1
  • 9
  • 16

1 Answers1

2

Instead of storing the OperationContext, wrap it in an abstraction that can be replaced making sure that the facilities presented by the context that you require are on the abstraction - something like this

interface IContextService
{
    Message RequestMessage{ get;}
    string SessionId{ get;}
} 

Then have an implementation that uses the real OperationContext

class ContextService : IContextService
{
    public Message RequestMessage
    {
        get
        {
             return OperationContext.Current.RequestContext.RequestMessage;
        }
    }

    public string SessionId
    {
        get
        {
             return OperationContext.Current.SessionId;
        }
    }
} 

If you inject an IContextService into your class you can now uit test by providing a fake version

Richard Blewett
  • 6,089
  • 1
  • 18
  • 23
  • Actually that's almost exactly what I'm doing except instead of using OperationContext.Current, I am using the instance of OperationContext that passed into the ctor of that class. I guess the change for me would be simply to use the Current property instead of an instance var. This makes the original question irrelevant even when using DI for tests. Thanks for making me realize this! – Mohammed Ali May 14 '12 at 02:59