我們有多個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