Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何以及在何处使用unity PerRequestLifetimeManager处理dbcontext_C#_Entity Framework_Asp.net Web Api_Unity Container - Fatal编程技术网

C# 如何以及在何处使用unity PerRequestLifetimeManager处理dbcontext

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

我使用unity IOC将dbcontext注入Web API中的相关类中。我正在使用自定义的lifetime manager,如下所示:

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
,并将生命周期管理留给它。微软最了解如何管理这些物品,并在时机成熟时处理它们。有什么想法吗?