关于.net:如何在-ASPNET-Core-中使用-FromServices

34次阅读

共计 2207 个字符,预计需要花费 6 分钟才能阅读完成。

ASP.NET Core 中内置了对依赖注入的反对,能够应用 依赖注入 的形式在运行时实现组件注入,这样能够让代码更加灵便,测试和可保护,通常有三种形式能够实现依赖注入。

  • 构造函数注入
  • 属性注入
  • 办法注入

构造函数 这种注入形式在 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<ISecurityService, SecurityService>();

            services.AddControllersWithViews();}

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


    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly ISecurityService _securityService;

        public HomeController(ILogger<HomeController> 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<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {_logger = logger;}

        public IActionResult Index([FromServices] ISecurityService securityService)
        {var isSuccess = securityService.Validate(string.Empty, string.Empty);

            return View();}
    }

总的来说,如果你只想在某些 Action 上而不是整个 Controller 中应用依赖注入,那么应用 FromServices 将是一个十分好的抉择,而且还能够让你的代码更加洁净,更加可保护。

译文链接:https://www.infoworld.com/art…

正文完
 0