【发布时间】:2009-01-26 18:06:20
【问题描述】:
我在 HttpApplicationState 对象上有一个扩展方法,用于将我的 IoC 容器从应用程序中取出。如果容器不存在,同样的代码也会创建容器。
我有两个问题:
- 我的代码是否真的像我预期的那样是线程安全的
- 这是否被认为是处理应用程序状态的最佳实践
代码如下:
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 将自己暴露为静态类,所以我永远不必担心它不存在。
标签: c# asp.net multithreading