.net核心在代码中的任何位置手动解决依赖关系 [英] .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
Another Idea is to add a static property and initialize its value in 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核心在代码中的任何位置手动解决依赖关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!