如何在 ASP.NET Core 中使用 FromServices

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 : AttributeIBindingSourceMetadata
    {
        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/article/3451821/how-to-use-the-fromservices-attribute-in-aspnet-core.html


本文分享自微信公衆號 - 一線碼農聊技術(dotnetfly)。
如有侵權,請聯繫 [email protected] 刪除。
本文參與“OSC源創計劃”,歡迎正在閱讀的你也加入,一起分享。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章