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

Is dependency injected DbContext shared between all classes that use it within a given request instance?

我想知道 Ninject 究竟是如何处理以下场景中的 EF DbContext 注入的。

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

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

有一个 API 控制器接受 DbContext 以及一个注入的 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,而 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?

如果是这样,那么控制器构造函数在获取上下文并创建 UnitOfWork classes (pattern from here) 之间没有区别(DbContext 明智)

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).