title: WCF Percall mode and threadstatic variables
body: <p>We have multiple WCF services all working with InstanceContextMode=PerCall and all WCF service instances are generated by employing Unity (IOC) and implementing IInstanceProvider. </p>
  
  <p>A correlation identifier is used to audit all method calls and database processes with the same identifier.</p>
  
  <p>In order to achieve this, an endpoint behavior is created by implementing IDispatchBehavior and in AfterReceiveRequest method, a guid is generated and assigned to a ThreadStatic (<code>CommonData</code>) property. This property can be access in all layers of the application. The following code block shows the population of CommonData, and the CommonData class;</p>
  
  <pre><code>public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
          {
              CommonData.ClearDictionary();
              //the lines between are deleted as they are not relevant to the question
  
              CommonData.Current.Add(MessageHeaderCodes.CorrelationId, Guid.NewGuid().ToString());    
              return null;
          }
  </code></pre>
  
  <p>and commondata class:</p>
  
  <pre><code>public class CommonData
      {            
          [ThreadStatic]
          private static Dictionary&lt;string, string&gt; headerData;    
  
          public static Dictionary&lt;string, string&gt; Current
          {
              get
              {
                  if (headerData == null)
                  {
                      headerData = new Dictionary&lt;string, string&gt;();
                  }
                  return headerData;
              }            
          }
  
          private CommonData()
          {
  
          }
  
          public static string GetHeader(string header)
          {
              string headerValue = string.Empty;
              KeyValuePair&lt;string, string&gt; headerKeyValuePair = CommonData.Current.SingleOrDefault(p =&gt; p.Key == header);
              headerValue = headerKeyValuePair.Value;
              return headerValue;
          }
  
          public static void ClearDictionary()
          {
              Current.Clear();
          }
      }
  </code></pre>
  
  <p>The problem here is the following;
  In some of the services, developers reported that the correlation identifier returns null. Since the problem is intermittant it is not possible to have a full stack trace at the moment. Also, they stated that reseting IIS resolves this problem temporarily.</p>
  
  <p>Any help is appreciated...</p>