其他分享
首页 > 其他分享> > 在给定的请求实例中使用依赖注入的DbContext是否在所有使用它的类之间共享?

在给定的请求实例中使用依赖注入的DbContext是否在所有使用它的类之间共享?

作者:互联网

我想知道Ninject在以下情况下到底如何处理EF DbContext注入.

有一个实用程序类,它将DbContext作为参数,并执行一些需要dbContext的工作:

public class SomeClass : ISomeClass
{
    public SomeClass(MyDbContext context)
    {
        //the context is dependency injected
    }
}

有一个采用DbContext的API控制器以及一个ISomeClass的注入实例(这也需要DbContext)

    public class SomeController
    {

        public SomeController(MyDbContext context, ISomeClass someClass)
        {
            //this controller uses db context for some simple actions and someclass for some more complex actions
        }
    }

绑定选项设置为:

kernel.Bind< MyDbContext>().ToSelf().InRequestScope();

现在的问题是

实例化SomeController时,SomeClass的实例是否共享MyDbContext的相同实例?
另外,如果SomeClass注入了SomeSubClass,而MyDbContext也注入了构造函数,那将是同一上下文实例吗?

它是这样工作的吗?

An http request comes in and requires creating controller and its
dependencies that require DbContext, so since we are set to
InRequestScope, lets return the same instance to rule them all?

如果是这样,则控制器构造器之间没有区别(明智的DbContext),该构造器接受上下文并像这样创建UnitOfWork类(pattern from here)

public class SomeController(MyDbContext context)
{
   this.someUnitOfWork = new SomeUnitOfWork(context);
}

还有一个将工作单位作为注入参数

public class SomeController(MyDbContext context, ISomeUnitOfWork someUnit){}

在这里,唯一的区别是与SomeUnitOfWork实现的紧密结合吗?

解决方法:

An http request comes in and requires creating controller and its
dependencies that require DbContext, so since we are set to
InRequestScope, lets return the same instance to rule them all?

是.这就是InRequestScope所做的.

https://github.com/ninject/Ninject.Web.Common/wiki/InRequestScope具有所有有趣的细节:

The main reason for using InRequestScope() is to make sure that a
single instance of an object is shared by all objects created via the
Ninject kernel for that HTTP request (e.g. to share an object that is
expensive to create).

标签:dependency-injection,ninject,c,asp-net-mvc,entity-framework
来源: https://codeday.me/bug/20191111/2018018.html