首页 新闻 搜索 专区 学院

没加 await 调用 async 方法遇到问题:"Cannot access a disposed object. Object name: 'IServiceProvider'"

0
悬赏园豆:30 [已解决问题] 解决于 2022-11-29 23:00

异步方法所在的类的构造函数注入了 IServiceProvider,通过它解析实例

await using var scoped = _scopeFactory.CreateAsyncScope();
var sp = scoped.ServiceProvider;
var db = sp.GetRequiredService<BlogDbContext>();

运行时报错

System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'IServiceProvider'.
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ThrowHelper.ThrowObjectDisposedException()
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.CreateAsyncScope(IServiceProvider provider)
dudu的主页 dudu | 高人七级 | 园豆:34971
提问于:2022-11-29 22:57
< >
分享
最佳答案
0

参考 Multi-Threaded Entity Framework Core Samples,用 IServiceScopeFactory 解决了问题。

构造函数注入 IServiceScopeFactory,然后

await using var scoped = _scopeFactory.CreateAsyncScope();
var sp = scoped.ServiceProvider;
var db = sp.GetRequiredService<BlogDbContext>();
dudu | 高人七级 |园豆:34971 | 2022-11-29 22:59
dudu | 园豆:34971 (高人七级) | 2022-11-30 09:28
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册