当使用从另一个服务注入到服务中的DbContext时,我得到了以下错误:
ObjectDisposedException: Cannot access a disposed object.
我的DbContext的生命周期是Scoped,我的服务的生命周期是Transient,但是将它们改为Singleton (我们不想要的)并不能解决这个问题。
有趣的是,错误似乎是随机发生的。有时没有错误,一切都运行得很好。
关于这个错误,当我的Angular应用程序开始向后端发出请求时,我(也是随机地)在启动后立即获得一个InvalidOperationException。
"An attempt was made to use the context while it is being configured. A DbContext instance cannot be used inside OnConfiguring since it is still being configured at this point."
我的代码:
public class MyService1 {
private static IMyService2 _myService2;
public MyService1(IMyService2 myService2){
_myService2 = myService2;
}
public async Task DoSomethingWithMyService2() {
await _myService2.DoSomething(new MyEntity());
}
}public class MyService2 : IMyService2 {
private MyDbContext _dbContext;
public MyService2(MyDbContext myDbContext) {
_dbContext = myDbContext;
}
public async Task DoSomething(MyEntity myEntity) {
await _dbContext.MySet.AddAsync(myEntity); // <-- ObjectDisposedException
await _dbContext.SaveChangesAsync();
}
}发布于 2020-06-04 19:42:09
回答我自己的问题:罪魁祸首是MyService2在注入到MyService1之后被存储在static字段中。
因为DbContext的生命周期是Scoped,所以它将在向服务发出初始请求后被释放。但是,该服务将存在于整个应用程序的生命周期中,并引用其处理的DbContext。
(我不完全确定后者(关于应用程序的生命周期),因为MyService1本身也是Transient。也许其他人可以解释这是如何工作的。)
https://stackoverflow.com/questions/62193766
复制相似问题