C# 如何以及在何处使用unity PerRequestLifetimeManager处理dbcontext
我使用unity IOC将dbcontext注入Web API中的相关类中。我正在使用自定义的lifetime manager,如下所示:C# 如何以及在何处使用unity PerRequestLifetimeManager处理dbcontext,c#,entity-framework,asp.net-web-api,unity-container,C#,Entity Framework,Asp.net Web Api,Unity Container,我使用unity IOC将dbcontext注入Web API中的相关类中。我正在使用自定义的lifetime manager,如下所示: public class PerRequestLifetimeManager : LifetimeManager { private readonly object key = new object(); public override object GetValue() { if (HttpContext.Cur
public class PerRequestLifetimeManager : LifetimeManager
{
private readonly object key = new object();
public override object GetValue()
{
if (HttpContext.Current != null &&
HttpContext.Current.Items.Contains(key))
return HttpContext.Current.Items[key];
else
return null;
}
public override void RemoveValue()
{
if (HttpContext.Current != null)
HttpContext.Current.Items.Remove(key);
}
public override void SetValue(object newValue)
{
if (HttpContext.Current != null)
HttpContext.Current.Items[key] = newValue;
}
}
这被注入global.asax中,如下所示:
//上下文-每个http请求一个上下文
RegisterType(新PerRequestLifetimeManager())
在dbcontext类中,我们有:
public class BudgetControlDbContext : DbContext, IBudgetControlDbContext
{
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
this._isDisposed = true;
}
public bool IsDisposed
{
get { return this._isDisposed; }
}
}
问题:
现在,如何处理dbcontext以及代码应该在哪里?这值得一读:我认为最好使用Unit.Mvc5 nuget包提供的
PerRequestLifetimeManager
,并将生命周期管理留给它。微软最了解如何管理这些物品,并在时机成熟时处理它们。有什么想法吗?