如何在.NET Core中获取IServiceProvider的实例?

编程入门 行业动态 更新时间:2024-10-21 23:03:25
本文介绍了如何在.NET Core中获取IServiceProvider的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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: https ://github/aspnet/DependencyInjection/blob/master/src/DI/ServiceCollection.cs

This is the default implementation of IServiceCollection from Microsoft: github/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的实例?

本文发布于:2023-11-14 09:25:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586839.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   如何在   Core   NET   IServiceProvider

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!