Store data in WCF Operation Context.Is ThreadStatic safe?


WCF infrastructure allows you to store context sensitive data in InstanceContext of the service instance similarly like we do in HttpContext of MVC. For that you should implement from IExtension and plug that class into WCF’s infrastructure.

public class WcfOperationContext : IExtension<OperationContext>
    private readonly IDictionary<string, object> items;

    private WcfOperationContext()
        items = new Dictionary<string, object>();

    public IDictionary<string, object> Items
        get { return items; }

    public static WcfOperationContext Current
            WcfOperationContext context = OperationContext.Current.Extensions.Find<WcfOperationContext>();
            if (context == null)
                context = new WcfOperationContext();
            return context;

    public void Attach(OperationContext owner) { }
    public void Detach(OperationContext owner) { }

Which you could use like that:
WcfOperationContext.Current.Items["data"] = "My Data";
string user = WcfOperationContext.Current.Items["data"] as string;

Is ThreadStatic safe?

I found that we miss the data or current context when we make async call with multiple thread switching. To handle such scenario you can try to use CallContext. It’s supposed to be used in .NET remoting but it should also work in such scenario.

Set the data in the CallContext:

DataObject data = new DataObject() { RequestId = "1234" };
CallContext.SetData("DataSet", data);

Retrieving shared data from the CallContext:

var data = CallContext.GetData("DataSet") as DataObject;

// Shared data object has to implement ILogicalThreadAffinative

public class DataObject : ILogicalThreadAffinative
  public string Message { get; set; }
  public string Status { get; set; }

Why ILogicalThreadAffinative ?

When a remote method call is made to an object in another AppDomain,the current CallContext class generates a LogicalCallContext that travels along with the call to the remote location.

Only objects that expose the ILogicalThreadAffinative interface and are stored in the CallContext are propagated outside the AppDomain.

Leave a Reply

Your email address will not be published. Required fields are marked *