gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:30:26 30 4
gpt4 key购买 nike

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

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

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

有一个 API Controller 接受 DbContext 以及一个注入(inject)的 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
}
}

绑定(bind)选项设置为:

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

现在,问题是

在实例化SomeController时,SomeClass的实例是否共享同一个MyDbContext实例?另外,如果 SomeClass 注入(inject)了 SomeSubClass,而 SomeSubClass 也注入(inject)了 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 类 (pattern from here) 的 Controller 构造函数之间没有区别(DbContext 方面)

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

还有一个将工作单元作为注入(inject)参数的

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

关于c# - 依赖注入(inject) DbContext 是否在给定请求实例中使用它的所有类之间共享?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45054744/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com