zoukankan      html  css  js  c++  java
  • 避免在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/)。

  • 相关阅读:
    c# PrintDocument 设置自定义纸张大小的示例
    C#获取本地打印机列表,并将指定打印机设置为默认打印机
    水晶报表自定义纸张大小打印 (Crystal Report Print with custom paper size)
    c#打印机设置,取得打印机列表及相应打印机的所有纸张格式
    在C#中设置打印机纸张大小
    打印grid
    获取List集合中最大值的方法
    mysql使用索引优化查询效率
    mysql数据库中标的key的含义
    mysql数据库添加索引优化查询效率
  • 原文地址:https://www.cnblogs.com/redmoon/p/5205488.html
Copyright © 2011-2022 走看看