【发布时间】:2020-09-23 09:16:54
【问题描述】:
当使用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();
}
}
【问题讨论】:
标签: asp.net-core entity-framework-core dbcontext asp.net-core-2.1