我喜欢HTTPContext.Current的工作方式。有没有办法实现一个与HTTPContextBase没有关系的类似对象?基本上,我想创建一个UserContext。然后在DAL中,我可以简单地查询此UserContext以获取特定于用户的信息。这个对象必须是线程安全的,并且可以在ASP.NET环境(因此线程静态属性不起作用)和控制台/库环境中工作。
发布于 2011-01-13 08:43:24
HttpContext.Current是一个单例。线程安全实现如下所示:
using System;
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() {}
public static Singleton Current
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}然而,使用单例模式并不是一个好主意。它几乎是“反模式”的。这会阻碍单元测试。更好的做法是使用依赖注入容器。http://en.wikipedia.org/wiki/Dependency_injection
https://stackoverflow.com/questions/4675597
复制相似问题