首页 新闻 会员 周边 捐助

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

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

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

var db = _serviceProvider.GetRequiredService();

运行时报错

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 | 高人七级 | 园豆:30925
提问于: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 | 高人七级 |园豆:30925 | 2022-11-29 22:59
dudu | 园豆:30925 (高人七级) | 2022-11-30 09:28
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册