首页 新闻 会员 周边

.netcore AutoFac注入DbContext类型的生命周期问题

0
悬赏园豆:20 [已解决问题] 解决于 2019-05-18 16:52

在.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的作用域来看,不应该出现这个问题。请问如何解决?

Code_Song的主页 Code_Song | 初学一级 | 园豆:51
提问于:2019-01-14 14:51
< >
分享
最佳答案
0

If you are using dependency injection, you should let the dependency injection container take care of disposing context instances

如果你在使用依赖注入,你应该让依赖注入容器来管理 Context 实例的生命周期。也就是说,你的第二个 using 是不必要的。

收获园豆:10
不如隐茶去 | 小虾三级 |园豆:559 | 2019-01-15 12:19
其他回答(1)
0

using结束释放了scope,但是你异步里面还在使用,所以冲突了吧,你看看是不是可以从这个方面入手解决一下这个问题

收获园豆:10
浅草青晨 | 园豆:904 (小虾三级) | 2019-01-14 15:45
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册