我们可以在 .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.
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/