在应用开发中,我们经常需要设置一些上下文(Context)信息,这些上下文信息一般基于当前的会话(Session),比如当前登录用户的个人信息;或者基于当前方法调用栈,比如在同一个调用中涉及的多个层次之间数据。在这篇文章中,我创建了一个称为ApplicationContext的组件,对上下文信息进行统一的管理。[Source Code从这里下载]
如何实现对上下文信息的存储,对于Web应用来说,我们可以借助于HttpSessionState;对于GUI应用来讲,我们则可以使用CallConext。ApplicationContext完全是借助于这两者建立起来的,首先来看看其定义:
using System;
using System.Collections.Generic;
using System.Runtime.Remoting.Messaging;
using System.Web;
namespace Artech.ApplicationContexts
6: {
7: [Serializable]
object>
9: {
;
11:
static ApplicationContext Current
13: {
14: get
15: {
null != HttpContext.Current)
17: {
null == HttpContext.Current.Session[ContextKey])
19: {
new ApplicationContext();
21: }
22:
as ApplicationContext;
24: }
25:
null == CallContext.GetData(ContextKey))
27: {
new ApplicationContext());
29: }
as ApplicationContext;
31: }
32: }
33: }
34: }