我正在尝试向 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?
}
当上面的代码执行时,我希望 isSame
的值为 false
,但它实际上是 true
。这是为什么? SomeDbContext
在使用 AddDbContext()
注册时具有作用域的生命周期,因此当它的作用域被释放并在第二个作用域中重新创建时,它应该被销毁。
最佳答案
您的测试不正确。尽管您正在创建两个独立的作用域,但实际上并没有使用它们。这是一个工作版本:
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?
}
请注意在解析依赖项时如何使用 scope.ServiceProvider
而不是 someServiceProvider
。
我在文档中找到的最接近的是 Call services from main .尽管该示例显示了 Main
方法,但它也确实演示了所使用的 IServiceProvider
如何来自范围本身。
关于c# - 为什么 DI 会为两个不同的范围返回相同的 DbContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57241830/