我们有多个WCF服务,都使用InstanceContextMode = PerCall,并且所有WCF服务实例都是通过使用Unity(IOC)并实现IInstanceProvider来生成的。WCF Percall模式和线程静态变量
相关标识符用于审核具有相同标识符的所有方法调用和数据库进程。
为了实现此目的,通过实现IDispatchBehavior创建端点行为,并在AfterReceiveRequest方法中,生成一个GUID并将其分配给ThreadStatic(CommonData
)属性。该属性可以在应用程序的所有层中访问。以下代码块显示CommonData和CommonData类的总体;
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;
}
和commondata类:
public class CommonData
{
[ThreadStatic]
private static Dictionary<string, string> headerData;
public static Dictionary<string, string> Current
{
get
{
if (headerData == null)
{
headerData = new Dictionary<string, string>();
}
return headerData;
}
}
private CommonData()
{
}
public static string GetHeader(string header)
{
string headerValue = string.Empty;
KeyValuePair<string, string> headerKeyValuePair = CommonData.Current.SingleOrDefault(p => p.Key == header);
headerValue = headerKeyValuePair.Value;
return headerValue;
}
public static void ClearDictionary()
{
Current.Clear();
}
}
这里的问题是以下; 在一些服务中,开发人员报告说相关标识符返回null。由于问题是间歇性的,因此目前不可能有完整的堆栈跟踪。此外,他们表示重置IIS可以暂时解决此问题。
任何帮助表示赞赏...
你究竟如何检索标识符(我猜GetHeader方法)? – Bond
我没有从客户端获取标识符,我只是在AfterReceiveRequest方法中为每个调用创建一个新的标识符; CommonData.Current.Add(MessageHeaderCodes.CorrelationId,Guid.NewGuid()。ToString()); – daryal
是的,但你尝试稍后以某种方式检索它?怎么样?如果不是 - 那么究竟什么是空的? – Bond