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