从 https://github.com/dotnet/runtime 中的对应源码 发现 ServiceProviderEngineScope
实现了 IServiceScopeFactory
internal sealed class ServiceProviderEngineScope : IServiceScope, IServiceProvider, IAsyncDisposable, IServiceScopeFactory
{ }
从 ServiceProvider 的实现源码 ServiceProvider.cs#L187 发现 CreateScope
方法的实现就是创建 ServiceProviderEngineScope
实例
internal IServiceScope CreateScope()
{
if (_disposed)
{
ThrowHelper.ThrowObjectDisposedException();
}
return new ServiceProviderEngineScope(this, isRootScope: false);
}
于是通过下面的代码解决了问题
IServiceCollection services = new ServiceCollection();
var serviceProvider = services.BuildServiceProvider();
var scopeFactory = (IServiceScopeFactory)serviceProvider.CreateScope();
IContactInfoRulesService contactInfoRulesService = new ContactInfoRulesService(scopeFactory);