在.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的作用域来看,不应该出现这个问题。请问如何解决?
- Using StoreGeneratedPattern.Identity with database
- Giving database context to object Factory
- Autofac registers components multiple times
- Inject a dependency in a SeriLog enricher with aut
- How can i have a IServiceProvider available in Val
- .netCore 控制台程序输出配置问题
- .NetCore Host.CreateDefaultBuilder 源码
- vs2019 docker打包.netcore
- netcore3.1 WebApi独立运行跨域设置无效
- Autofac Exception: Cannot resolve parameter of con
- How Can I Use Custom Validation Attributes on Chil
- Custom ControllerFactory with autofac
- what is the best practice to set up DbContext in S
如果你在使用依赖注入,你应该让依赖注入容器来管理 Context 实例的生命周期。也就是说,你的第二个
using
是不必要的。using结束释放了scope,但是你异步里面还在使用,所以冲突了吧,你看看是不是可以从这个方面入手解决一下这个问题