温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

ASP.NET Core 中FromServices如何使用

发布时间:2021-07-15 15:49:24 来源:亿速云 阅读:154 作者:Leah 栏目:web开发

本篇文章给大家分享的是有关 ASP.NET Core 中FromServices如何使用,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

构造函数 这种注入方式在 ASP.NET Core 中应用的是最广的,可想而知,只用这种方式也不是 放之四海而皆准 ,比如说,我不希望每次 new  class  的时候都不得不注入,换句话说,我想把依赖注入的粒度缩小,我希望只对某一个或者某几个方法单独实现注入,而不是全部,首先这能不能实现呢?实现肯定是没有问题的,只需用  FromServices 特性即可,它可以实现对 Controller.Action 单独注入。

这篇文章我们将会讨论如何在 ASP.NET Core 中使用 FromServices 特性实现依赖注入,同时我也会演示最通用的 构造函数注入 。

使用构造函数注入接下来先通过 构造函数 的方式实现依赖注入,考虑下面的 ISecurityService 接口。

public interface ISecurityService { bool Validate(string userID, string  password); } public class SecurityService : ISecurityService { public bool  Validate(string userID, string password) { //Write code here to validate the  user credentials return true; } }

要想实现依赖注入,还需要将 SecurityService 注入到 ServiceCollection 容器中,如下代码所示:

// This method gets called by the runtime. Use this method to add services to  the container. public void ConfigureServices(IServiceCollection services) {  services.AddTransient(); services.AddControllersWithViews(); }

下面的代码片段展示了如何通过 构造函数 的方式实现注入。

public class HomeController : Controller { private readonly ILogger _logger;  private readonly ISecurityService _securityService; public  HomeController(ILogger logger, ISecurityService securityService) { _logger =  logger; _securityService = securityService; } public IActionResult Index() { var  isSuccess = _securityService.Validate(string.Empty, string.Empty); return  View(); } }

FromServicesAttribute 简介FromServicesAttribute 特性是在 Microsoft.AspNetCore.Mvc  命名空间下,通过它可以直接将service注入到action方法中,下面是 FromServicesAttribute 的源码定义:

[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited  = true)] public class FromServicesAttribute : Attribute, IBindingSourceMetadata  { public FromServicesAttribute(); public BindingSource BindingSource { get; }  }

使用 FromServices 依赖注入接下来将 FromServices 注入到 Action  方法参数上,实现运行时参数的依赖解析,知道这些基础后,现在可以把上一节中的 构造函数注入 改造成 FromServices注入,如下代码所示:

public class HomeController : Controller { private readonly ILogger _logger;  public HomeController(ILogger logger) { _logger = logger; } public IActionResult  Index([FromServices] ISecurityService securityService) { var isSuccess =  securityService.Validate(string.Empty, string.Empty); return View(); } }

以上就是 ASP.NET Core 中FromServices如何使用,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI