阿牛 - 专注.NET开发

如果梦想与实现之间有一道不可逾越的鸿沟,那么“执行力”就是跨越这道鸿沟的桥梁。

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
/// <summary>
    /// 在Web Request期间只存在唯一实例的类
    /// 使用了Lazy
    /// </summary>
    public class SingletonPerRequest
    {
        public object Data;

        public static readonly string Key = "SingletonPerRequest.Key";

        public static SingletonPerRequest Current
        {
            get
            {
                SingletonPerRequest instance = (SingletonPerRequest)HttpContext.Current.Items[Key];
                if (instance==null)
                {
                    instance = new SingletonPerRequest();
                    HttpContext.Current.Items[Key] = instance;
                }
                return instance;
            }
        }
    }

    /// <summary>
    /// 在一个执行线程中只存在唯一实例的类
    /// 使用了Lazy
    /// </summary>
    public class SingletonPerThread
    {
        public object Data;

        public static readonly string Key = "SingletonPerThread.Key";

        public static SingletonPerThread Current
        {
            get
            {
                SingletonPerThread instance = (SingletonPerThread)CallContext.GetData(Key);
                if (instance == null)
                {
                    instance = new SingletonPerThread();
                    CallContext.SetData(Key, instance);
                }
                return instance;
            }
        }
    }

这只是个示例,你可以将它改为泛型类,以编写更安全的代码.

此外,CallContext在Web/Win中,可以移植,所以Web中也建议使用第二种方案.

posted on 2009-11-11 15:26  阿牛-专注金融行业开发  阅读(352)  评论(0编辑  收藏  举报