避免在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/)。

posted @ 2016-02-21 20:26  朱永光  阅读(2026)  评论(2编辑  收藏  举报