在.netcore项目中,通过AutoFac注入DbContext为InstancePerDependency。
在调用时通过创建不同的scope,得到的实例是不一样的。代码如下
using (var scope = IocContainer.AutofacContainer.BeginLifetimeScope())
{
using (MySqlDbContext mySqlDbContext = scope.Resolve<MySqlDbContext>())
{
//TODO
}
}
在一个请求的业务里,需要开启多个异步Task操作DbContext.这个时候,会出现异常
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
根据AutoFac注入的类型为InstancePerDependency,和scope的作用域来看,不应该出现这个问题。请问如何解决?