如何在 .NET Core 中获取 IServiceProvider 的实例? [英] How to get an instance of IServiceProvider in .NET Core?
问题描述
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
本身的实例可以通过调用IServiceCollection
的BuildServiceProvider
方法获得.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.
我想在没有 Setup
方法的情况下创建 IServiceProvider
的实例.我需要它来解决集成测试程序集中的依赖项.在这种情况下完全可以得到它吗?
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
的默认实现:https://github.com/aspnet/DependencyInjection/blob/master/src/DI/ServiceCollection.cs
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 的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!