为什么DI为两个不同的范围返回相同的DbContext?

bur*_*1ce 1 c# dependency-injection asp.net-core

我试图将测试添加到ASP.NET Core项目,在该项目中在一个范围内创建对象,然后在另一个范围内读取对象。这是为了模拟用户在一个POST请求中创建对象,然后在另一个GET请求中读取对象。但是,我在正确模拟这种情况时遇到了麻烦。

我的测试代码中有这个

SomeDbContext firstContext;
bool isSame;
using (var scope = someServiceProvider.CreateScope()) {
   firstContext = someServiceProvider.GetService<SomeDbContext>();
}

using (var scope = someServiceProvider.CreateScope()) {
   var secondContext = someServiceProvider.GetService<SomeDbContext>();
   isSame = firstContext == secondContext; //should be false, right?
}
Run Code Online (Sandbox Code Playgroud)

我希望上面的代码执行时isSame具有一个值,false但实际上是true。这是为什么?SomeDbContext向其注册时具有作用域的生存期,AddDbContext()因此在处置其作用域并在第二个作用域中重新创建时,应将其销毁。

Kir*_*kin 7

您的测试不正确。尽管您要创建两个单独的范围,但实际上并没有使用它们。这是一个工作版本:

SomeDbContext firstContext;
bool isSame;
using (var scope = someServiceProvider.CreateScope()) {
   firstContext = scope.ServiceProvider.GetService<SomeDbContext>();
}

using (var scope = someServiceProvider.CreateScope()) {
   var secondContext = scope.ServiceProvider.GetService<SomeDbContext>();
   isSame = firstContext == secondContext; //should be false, right?
}
Run Code Online (Sandbox Code Playgroud)

注意解决依赖关系时如何scope.ServiceProvider使用而不是someServiceProvider

我能在文档中找到的最接近的东西是来自main的呼叫服务。尽管示例显示了该Main方法,但它的确演示了如何IServiceProvider使用示波器本身。