.net核心在代码中的任何位置手动解决依赖关系

编程入门 行业动态 更新时间:2024-10-12 20:24:19
本文介绍了核心在代码中的任何位置手动解决依赖关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

您知道如何在 core 中手动解决依赖性吗?

Do you know how to manually resolve dependencies in 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核心在代码中的任何位置手动解决依赖关系

本文发布于:2023-11-16 06:58:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1602025.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:核心   位置   代码   关系   net

发布评论

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

>www.elefans.com

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