异步方法所在的类的构造函数注入了 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)
参考 Multi-Threaded Entity Framework Core Samples,用 IServiceScopeFactory
解决了问题。
构造函数注入 IServiceScopeFactory
,然后
await using var scoped = _scopeFactory.CreateAsyncScope();
var sp = scoped.ServiceProvider;
var db = sp.GetRequiredService<BlogDbContext>();
stackoverflow 上发现一个参考:.NET Core IServiceScopeFactory.CreateScope() vs IServiceProvider.CreateScope() extension