我在HttpApplicationState对象上有一个扩展方法,用于让我的IoC容器脱离应用程序。如果该容器不存在,该代码也会创建该容器。ASP.NET线程 - 双重检查锁定
我有2个问题:
- 是我的代码实际上是线程安全的,因为我想让它是
- 这被认为是最好的做法来处理应用程序的状态
守则如下:
private const string GlobalContainerKey = "UnityContainerKey";
public static IUnityContainer GetContainer(this HttpApplicationState application)
{
var container = application[GlobalContainerKey] as IUnityContainer;
if (container == null)
{
try
{
application.Lock();
container = application[GlobalContainerKey] as IUnityContainer;
if (container == null)
{
container = new UnityContainer();
application[GlobalContainerKey] = container;
}
}
finally
{
application.UnLock();
}
}
return container;
}
除此之外,由于我从Unity转移到StructureMap和SM中,我将这个完整的问题作为一个静态类公开,因此我从不需要担心它不存在。 – 2009-02-15 23:43:50