I am getting the following error when using DbContext
injected into a service from another service:
ObjectDisposedException: Cannot access a disposed object.
The lifetime of my DbContext
is Scoped
and the lifetimes of my services is Transient
, but changing these other than to Singleton
(which we don't want) does not solve the issue.
Interestingly, the error occurs seemingly at random. Sometimes there are no errors and everything runs fine.
In relation to this error, I am (also randomly) getting a InvalidOperationException
right after startup, when my Angular app starts firing requests to the backend.
"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."
My code:
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();
}
}