首页 新闻 会员 周边

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

0
悬赏园豆:20 [已关闭问题] 关闭于 2019-01-14 12:45

在.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 11:45
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册