0
我喜欢HTTPContext.Current的工作方式。有什么办法可以实现一个与HTTPContextBase没有关系的类似对象吗?基本上,我想创建一个UserContext。然后在DAL中,我可以简单地查询此UserContext以获取用户特定的信息。该对象必须是线程安全的并且可以在ASP.NET环境(THREAD STATIC属性不起作用)和控制台/库环境中工作。像对象一样的HttpContext
我喜欢HTTPContext.Current的工作方式。有什么办法可以实现一个与HTTPContextBase没有关系的类似对象吗?基本上,我想创建一个UserContext。然后在DAL中,我可以简单地查询此UserContext以获取用户特定的信息。该对象必须是线程安全的并且可以在ASP.NET环境(THREAD STATIC属性不起作用)和控制台/库环境中工作。像对象一样的HttpContext
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;
}
}
}
但是使用Singleton模式不是好主意。这几乎是“反模式”。这阻碍了单元测试。而不是更好地使用依赖注入容器。 http://en.wikipedia.org/wiki/Dependency_injection
为什么`[ThreadStatic]`不能工作? – SLaks 2011-01-13 00:35:14
ThreadStatic将不起作用,因为如果它位于ASP.NET环境中,则可能发生线程切换。 – choudeshell 2011-01-13 01:24:59