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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值