由于我使用Unity,我错误地使用了PerThreadLifeTimeManager。我很快意识到ASP.Net线程模型不支持我想要实现的内容。基本上它使用一个线程池并回收线程,这意味着我每个线程只得到一个UnitOfWork!!然而,我想要的是每个Web请求一个工作单元。
通过一些搜索,我找到了这篇绝佳的文章。那正是我想要的,除了Unity部分,这相当容易实现。
以下是我对Unity的PerCallContextLifeTimeManager的实现:
public class PerCallContextLifeTimeManager : LifetimeManager
{
private const string Key = "SingletonPerCallContext";
public override object GetValue()
{
return CallContext.GetData(Key);
}
public override void SetValue(object newValue)
{
CallContext.SetData(Key, newValue);
}
public override void RemoveValue()
{
}
}
当然,我使用类似以下代码的方式将我的工作单元注册:
unityContainer
.RegisterType<IUnitOfWork, MyDataContext>(
new PerCallContextLifeTimeManager(),
new InjectionConstructor());
希望它能为某人节省一些时间。