如何在 ASP.NET Core 中使用 FromServices
ASP.NET Core 中內(nèi)置了對(duì)依賴注入的支持,可以使用 依賴注入 的方式在運(yùn)行時(shí)實(shí)現(xiàn)組件注入,這樣可以讓代碼更加靈活,測(cè)試和可維護(hù),通常有三種方式可以實(shí)現(xiàn)依賴注入。
構(gòu)造函數(shù)注入
屬性注入
方法注入
構(gòu)造函數(shù) 這種注入方式在 ASP.NET Core 中應(yīng)用的是最廣的,可想而知,只用這種方式也不是 放之四海而皆準(zhǔn) ,比如說(shuō),我不希望每次 new class 的時(shí)候都不得不注入,換句話說(shuō),我想把依賴注入的粒度縮小,我希望只對(duì)某一個(gè)或者某幾個(gè)方法單獨(dú)實(shí)現(xiàn)注入,而不是全部,首先這能不能實(shí)現(xiàn)呢?實(shí)現(xiàn)肯定是沒(méi)有問(wèn)題的,只需用 FromServices 特性即可,它可以實(shí)現(xiàn)對(duì) Controller.Action 單獨(dú)注入。
這篇文章我們將會(huì)討論如何在 ASP.NET Core 中使用 FromServices 特性實(shí)現(xiàn)依賴注入,同時(shí)我也會(huì)演示最通用的 構(gòu)造函數(shù)注入 。
使用構(gòu)造函數(shù)注入接下來(lái)先通過(guò) 構(gòu)造函數(shù) 的方式實(shí)現(xiàn)依賴注入,考慮下面的 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; } }
要想實(shí)現(xiàn)依賴注入,還需要將 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(); }
下面的代碼片段展示了如何通過(guò) 構(gòu)造函數(shù) 的方式實(shí)現(xiàn)注入。
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 簡(jiǎn)介FromServicesAttribute 特性是在 Microsoft.AspNetCore.Mvc 命名空間下,通過(guò)它可以直接將service注入到action方法中,下面是 FromServicesAttribute 的源碼定義:
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] public class FromServicesAttribute : Attribute, IBindingSourceMetadata { public FromServicesAttribute(); public BindingSource BindingSource { get; } }
使用 FromServices 依賴注入接下來(lái)將 FromServices 注入到 Action 方法參數(shù)上,實(shí)現(xiàn)運(yùn)行時(shí)參數(shù)的依賴解析,知道這些基礎(chǔ)后,現(xiàn)在可以把上一節(jié)中的 構(gòu)造函數(shù)注入 改造成 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(); } }
圖片
總的來(lái)說(shuō),如果你只想在某些Action上而不是整個(gè) Controller 中使用依賴注入,那么使用 FromServices 將是一個(gè)非常好的選擇,而且還可以讓你的代碼更加干凈,更加可維護(hù)。
譯文鏈接:https://www.infoworld.com/article/3451821/how-to-use-the-fromservices-attribute-in-aspnet-core.html