/// <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中也建议使用第二种方案.

相关文章:

  • 2021-12-24
  • 2021-10-18
  • 2022-01-04
  • 2022-03-09
  • 2022-02-12
  • 2022-12-23
猜你喜欢
  • 2021-08-20
  • 2021-09-04
  • 2021-06-30
  • 2022-12-23
  • 2022-03-08
  • 2022-02-10
  • 2021-08-26
相关资源
相似解决方案