.net core 在代码中的任何地方手动解析依赖 [英] .net core resolve dependency manually anywhere in the code
问题描述
您知道如何在 .net core 中手动解析依赖项吗?类似的东西
Do you know how to manually resolve dependencies in .net core? Something like
DependencyResolver.Resolve<ISomeService>()
更新我在一个没有注入的类中,我想从内部解决它,而不是到处传递变量
UPDATE I'm in a class that was not injected, I want to resolve it from the inside, rather than pass variables all over the place
推荐答案
在 ConfigureServices
中添加你的依赖项
Add your dependency in ConfigureServices
as below
public void ConfigureServices(IServiceCollection services){
//AddSingleton or AddTransient based on your requirements
services.AddTransient<ISomeService, ConcreteService>();
}
在您的控制器或任何地方,在构造函数中添加 IServiceProvider
,如下所示:
In your controller or anywhere, add IServiceProvider
in the constructor like below:
using Microsoft.Extensions.DependencyInjection;
...
public class HomeController
{
...
public HomeController(IServiceProvider serviceProvider)
{
var service = serviceProvider.GetService<ISomeService>();
}
}
@Shazam,以下是根据您的评论提出的一些说明或建议:
@Shazam, Here are some notes or suggestions based on your comment:
如果由于此类中可能没有构造函数而无法注入,我建议您在函数中添加一个参数并从外部传递解析的依赖项
If you can not inject because you might not have a constructor in this class, I woud suggest to add a paramter to your function and pass the resolved dependency from outside
另一个想法是在ConfigureServices
例如:
public static class MyClass
{
public static ISomeService MyServiceObj { set; get; }
....
}
在你的 ConfigureServices
public void ConfigureServices(IServiceCollection services){
services.AddTransient<ISomeService, ConcreteService>();
MyClass.MyServiceObj = services.GetService<ISomeService>();
}
希望对您有所帮助,如果您仍然不确定如何操作,请评价我的回答或给我留言
Hope this helps, please rate my answer or leave me a comment if you still in doubt how to do it
这篇关于.net core 在代码中的任何地方手动解析依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!