在Controller中获取服务

posted at 2021.3.20 18:36 by 风信子

ASP.NET CoreController是定义Web API的核心方法,在Controller中获取服务有以下几种途径:

1、使用构造函数参数。

2、使用HttpContext.RequestServices属性。

3、使用FormServicesAttribute标注Action的入参。 

这些方法的示例代码如下:

    [ApiController]

    [Route("[controller]")]

    public class MyController : ControllerBase

    {

        private readonly IMyService _myService; 

        public MyController(IMyService myService)

        {

            _myService = myService;

        } 

        [HttpGet]

        public string Get([FromServices]IMyService myService2)

        {

            var myService3 = this.HttpContext

                         .RequestServices.GetService<IMyService>();

            var data1 = _myService.GetData();

            var data2 = myService2.GetData();

            var data3 = myService3.GetData();

            return "Ok";

        } 

  }

在实际的场景中,建议的方法是:当Controller的大部分Action都需要使用某个服务时,使用构造函数注入该服务;仅当个别Action需要使用某个服务时,使用FromServicesAttribute为其具体的Action注入服务;尽量避免使用HttpContext.RequestServices来获取服务,这样会使类难以编写单元测试。 

默认情况下,Controller实例本身的构造是由ASP.NET Core框架来负责的,而不是由容器负责,因此当使用第三方组件来扩展其他能力(如AOP、属性注入等)时,对于Controller本身并不会有效。要使用容器来负责Controller的构造,需要在Startup类的ConfigureServices方法中加入AddControllerAsServices方法,具体代码如下:     

        public Startup()

        {

        public void ConfigureServices(IServiceCollection services)

        {

            services.AddControllers().AddControllersAsServices();

        }

        } 

Tags: , , ,

IT技术

添加评论

  Country flag

biuquote
  • 评论
  • 在线预览
Loading

kesintisiz tv