在ASP.NET Core中访问类装饰器的配置属性

时间:2019-05-27 11:00:46

标签: c# asp.net-web-api asp.net-core dependency-injection asp.net-core-2.2

基于此Question Here ,我正在研究将控制器绑定到某些 URL 的解决方案。这些网址是在appsettings.json中配置的。

由于该解决方案基于装饰器,因此我正在寻找一种为装饰器注入IConfiguration对象的方法。

示例:

[PortActionConstraint(configuration.GetValue<string>("Product1:Port")]
[Route("api/[controller]")]
[ApiController]
public class Product1Controller : ControllerBase

简而言之,如何将任何接口的IConfiguration注入类装饰器?

1 个答案:

答案 0 :(得分:3)

最简单的解决方案是在约束实现内部使用服务定位器模式来检索IConfiguration对象。

因此,在“ IsValidForRequest”方法中,可通过HTTP上下文检索服务:

public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
{
    var configuration = routeContext.HttpContext.RequestServices.GetService<IConfiguration>();

    // do something with the configuration
}

或者,您也可以实现IActionConstraintFactory,这将允许您使用构造函数注入来正确解析依赖项。不过,这将需要您自己实现IActionConstraint。因此,对于这个简单的要求,将ActionMethodSelectorAttribute与服务定位器一起使用可能会更容易。

相关问题