一、问题
该问题经常出现在 ABP vNext 框架当中,要复现该问题十分简单,只需要你注入一个 IRepository<T,TKey> 仓储,在任意一个地方调用 IRepository<T,TKey>.ToList() 方法。
1
2
3
4
5
6
7
|
[Fact]
public void TestMethod()
{
var rep = GetRequiredService<IHospitalRepository>();
var result = rep.ToList();
}
|
例如上面的测试代码,不出意外就会提示 System.ObjectDisposedException 异常,具体的异常内容信息:
1
|
System.ObjectDisposedException : Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
|
其实已经说得十分明白了,因为你要调用的 DbContext 已经被释放了,所以会出现这个异常信息。