ITPub博客

首页 > 应用开发 > > .netcore AutoFac注入DbContext类型的生命周期问题

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

作者:youyouaq 时间:2019-08-30 10:18:06 0 删除 编辑

在.netcore项目中,通过AutoFac注入DbContext为InstancePerDependency。

在调用时通过创建不同的scope,得到的实例是不一样的。代码如下

using (var scope = IocContainer.AutofacContainer.BeginLifetimeScope())

{

using (MySqlDbContext mySqlDbContext = scope.Resolve())

{

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

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3050/viewspace-3127042/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-13

  • 博文量
    90
  • 访问量
    783