c# - 构造函数外的 DI

标签 c# dependency-injection .net-core

我们可以在 .NET Core 中即时请求依赖项吗?像这样的东西:

public void MyMethod() {
    var dep = DependencyMagic.Instantiate<MyDependency>();
}

我对第 3 方解决方案不感兴趣,但如果它完成了您的回答,请随时对它们发表评论。我只是使用 .NET Core 中内置的 DI。我不能使用 Activator因为我不知道依赖项的构造函数的签名是什么。

最佳答案

您需要使用 System.IServiceProvider 的实例。它定义了下一个方法:

// Gets the service object of the specified type.
public object GetService(Type serviceType)

在 .NET 核心中 this还提供了扩展方法:

public static T GetService<T>(this IServiceProvider provider)

Microsoft.Extensions.DependencyInjection.IServiceScope.ServiceProvider ( definition ) 是 IServiceProvider 接口(interface)的默认实现。

如果您的应用程序是一个 ASP.NET Core,那么通过 HttpContext 您可以检索 IServiceProvider 实例。来自 official文档:

The services available within an ASP.NET request from HttpContext are exposed through the RequestServices collection.

enter image description here

Request Services represent the services you configure and request as part of your application. When your objects specify dependencies, these are satisfied by the types found in RequestServices, not ApplicationServices.

Generally, you shouldn't use these properties directly, preferring instead to request the types your classes you require via your class's constructor, and letting the framework inject these dependencies. This yields classes that are easier to test (see Testing) and are more loosely coupled.

关于c# - 构造函数外的 DI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41597580/

相关文章:

java - 两个单独的 Maven 项目之间可以存在依赖关系吗?

java - 我可以将参数传递给 GWT 模块构造函数吗?

.net-core - 如何从 Visual Studio 2017 调试在 Minikube 上运行的 .Net Core 应用程序

c# - 为什么 img src 不能作为 <asp :Image ImageUrl does 工作

c# - 找不到命名空间名称 'DispatcherTimer'

使用 Lombok 和 Guice 注入(inject)进行 Java 链继承

.net-core - 是什么导致 Docker 镜像中出现 "Could not find data collector ' XPlat 代码覆盖率'”错误?

C# Julian 日期解析器

c# - 如何在 Resharper 中评估表达式,如 IntellijIdea(Alt+F8)

asp.net-core - 在 ASP.NET Core MVC 中提供一些静态文件的问题