整合 HttpSessionState(Web)與 CallContext(GUI/服務)統一管理上下文資料(如當前用戶資訊、調用鏈路共享資料)。
[Serializable]
public class ApplicationContext : Dictionary<string, object>
{
public const string ContextKey = "Artech.ApplicationContexts.ApplicationContext";
public static ApplicationContext Current
{
get
{
if (HttpContext.Current != null)
{
if (HttpContext.Current.Session[ContextKey] == null)
HttpContext.Current.Session[ContextKey] = new ApplicationContext();
return HttpContext.Current.Session[ContextKey] as ApplicationContext;
}
if (CallContext.GetData(ContextKey) == null)
CallContext.SetData(ContextKey, new ApplicationContext());
return CallContext.GetData(ContextKey) as ApplicationContext;
}
}
}
// 寫入
ApplicationContext.Current["UserName"] = "Foo";
// 讀取
var userName = ApplicationContext.Current["UserName"];
鍵值固定為 Artech.ApplicationContexts.ApplicationContext。Web 環境自動使用 Session,非 Web 環境落回 CallContext(跨 AppDomain 需序列化,故標記 [Serializable])。