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?
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