避免在ASP.NET Core中使用服務定位器模式


(此文章同時發表在本人微信公眾號“dotNET每日精華文章”,歡迎右邊二維碼來關注。)

題記:服務定位器(Service Locator)作為一種反模式,一般情況下應該避免使用,在ASP.NET Core更是需要如此。

Scott Allen在其博客網站上發表了一篇名為“Avoiding the Service Locator Pattern in ASP.NET Core”的文章解釋了這一模式會帶來的問題:導致應用程序無法完全基於控制反轉(依賴注入)容器。同時給出了在各種情況下的替代方案。

雖然可以把ASP.NET Core中提供的HttpContext.ApplicationServices或HttpContext.ReqeustServices作為服務定位器使用(如下代碼片段),但是應該避免這樣使用。

var provider = HttpContext.ApplicationServices;
var someService = provider.GetService(typeof(ISomeService));

在啟動的時候,注入自己的服務:

public class Startup
{
    public void ConfigureServices(IServiceCollection services) { }
  
    public void Configure(IApplicationBuilder app,
                          IAmACustomService customService)
    {
        // ....   
    }        
}

在中間件中有兩個地方可以注入服務(構造器和Invoke方法):

public class TestMiddleware
{
    public TestMiddleware(RequestDelegate next, IAmACustomService service)
    {
        // ...
    }
 
    public async Task Invoke(HttpContext context, IAmACustomService service)
    {
        // ...
    }    
}

在控制器中可以在構造器中注入服務:

public class HelloController : Controller
{
    private readonly IAmACustomService _customService;
 
    public HelloController(IAmACustomService customService)
    {
        _customService = customService;
    }
 
    public IActionResult Get()
    {
        // ...
    }
}

在控制器的操作方法中可以利用[FromServices]標記注入服務:

[HttpGet("[action]")]
public IActionResult Index([FromServices] IAmACustomService service)
{            
    // ...
}

在模型中同樣可以利用[FromServices]:

public class TestModel
{       
    public string Name { get; set; }
 
    [FromServices]
    public IAmACustomService CustomService { get; set; }
}

在視圖中可以利用@inject聲明來注入服務:

@inject IAmACustomService CustomService;
  
<div>
    Blarg   
</div>

其實在所有其他地方甚至過濾器中都可以充分利用依賴注入,可以參考:Action Filters, Service Filters, and Type Filtershttp://www.strathweb.com/2015/06/action-filters-service-filters-type-filters-asp-net-5-mvc-6/)。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM