Storing OperationContext.Current in an instance variable of a WCF service instance

I wanted to know whether it is advisable to store and reference the OperationContext.Current object in the instance variable of the WCF service host instance. The service host is set to InstanceContextMode.PerCall, so each new request gets its own instance.

I ask for this because WCF does not guarantee thread similarity. Sometimes WCF can start a request in one thread and end a request in another thread.

The OperationContext.Current object is stored in the local thread store. When a new thread is used for the same operation, WCF “propagates” to the new thread.

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

+3
source share
1 answer

Instead of saving, OperationContextwrap it with an abstraction that you can replace by making sure that the objects represented by the context you need are in the abstraction - something like this

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

Then execute an implementation that uses a real OperationContext

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

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

If you type IContextServicein your class, you can now test by providing a fake version

+2
source

All Articles