问题描述
IServiceProvider
是具有单个方法的接口:
IServiceProvider
is an interface with single method:
object GetService(Type serviceType);
用于创建在.NET Core本机DI容器中注册的类型的实例。
It's used to create instances of types registered in .NET Core native DI container.
IServiceProvider
本身的实例可以通过调用 BuildServiceProvider
方法获得 IServiceCollection
。 IServiceCollection
是 Startup
类中 ConfigureServices
方法的参数。框架似乎用 IServiceCollection
的实例神奇地调用了它。
An instance of IServiceProvider
itself can be obtained by calling a BuildServiceProvider
method of an IServiceCollection
. IServiceCollection
is a parameter of ConfigureServices
method in a Startup
class. It seems to be magically called with an instance of IServiceCollection
by the framework.
我想创建一个实例 IServiceProvider
完全没有 Setup
方法。我需要它来解决集成测试程序集中的依赖关系。在这种情况下,能否完全获得它?
I want to create an instance of IServiceProvider
without having Setup
method at all. I need it to resolve dependencies in an integration test assembly. Is it possible to get it at all in this scenario?
推荐答案
这是 IServiceCollection的默认实现
从Microsoft:
This is the default implementation of IServiceCollection
from Microsoft:https://github.com/aspnet/DependencyInjection/blob/master/src/DI/ServiceCollection.cs
看看代码,您应该可以只需调用以下命令即可获取 IServiceCollection
:
Looking at the code then you should be able to get an IServiceCollection
simply by calling:
var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
希望有帮助:)
这篇关于如何在.NET Core中获取IServiceProvider的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!