|
在應用開發中,我們經常需要設置一些上下文(Context)信息,這些上下文信息一般基于當前的會話(Session),比如當前登錄用戶的個人信息;或者基于當前方法調用棧,比如在同一個調用中涉及的多個層次之間數據。在這篇文章中,我創建了一個稱為ApplicationContext的組件,對上下文信息進行統一的管理。[Source Code從這里下載]
一、基于CallContext和HttpSessionState的ApplicationContext
如何實現對上下文信息的存儲,對于Web應用來說,我們可以借助于HttpSessionState;對于GUI應用來講,我們則可以使用CallConext。ApplicationContext完全是借助于這兩者建立起來的,首先來看看其定義:
1: using System;
2: using System.Collections.Generic;
3: using System.Runtime.Remoting.Messaging;
4: using System.Web;
5: namespace Artech.ApplicationContexts
6: {
7: [Serializable]
8: public class ApplicationContext:Dictionary<string, object>
9: {
10: public const string ContextKey = "Artech.ApplicationContexts.ApplicationContext";
11:
12: public static ApplicationContext Current
13: {
14: get
15: {
16: if (null != HttpContext.Current)
17: {
18: if (null == HttpContext.Current.Session[ContextKey])
19: {
20: HttpContext.Current.Session[ContextKey] = new ApplicationContext();
21: }
22:
23: return HttpContext.Current.Session[ContextKey] as ApplicationContext;
24: }
25:
26: if (null == CallContext.GetData(ContextKey))
27: {
28: CallContext.SetData(ContextKey, new ApplicationContext());
29: }
30: return CallContext.GetData(ContextKey) as ApplicationContext;
31: }
32: }
33: }
34: }
NET技術:如何實現對上下文(Context)數據的統一管理 [提供源代碼下載],轉載需保留來源!
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。