我有一个代码,控制器调用服务和服务使用工作单元来处理数据库。我使用Unity作为依赖注入。我需要在请求范围结束后自动处理unity(dbContext)。我没有在UnityCofig.cs中引用PerRequestLifetimeManager。有什么指针吗?
答案 0 :(得分:-1)
尝试创建新的派生类型的终身经理
public class PerHttpRequestLifetime : LifetimeManager
{
// This is very important part and the reason why I believe mentioned
// PerCallContext implementation is wrong.
private readonly Guid _key = Guid.NewGuid();
public override object GetValue()
{
return HttpContext.Current.Items[_key];
}
public override void SetValue(object newValue)
{
HttpContext.Current.Items[_key] = newValue;
}
public override void RemoveValue()
{
var obj = GetValue();
HttpContext.Current.Items.Remove(obj);
}
}
来源: MVC, EF - DataContext singleton instance Per-Web-Request in Unity