[英]Accessing Configuration Properties for the Class Decorators in ASP.NET Core
基于此问题 ,我正在研究将控制器绑定到某些URL的解决方案。 这些URL在appsettings.json
中配置。
由于该解决方案基于装饰器,因此我正在寻找一种为装饰器注入IConfiguration对象的方法。
范例:
[PortActionConstraint(configuration.GetValue<string>("Product1:Port")]
[Route("api/[controller]")]
[ApiController]
public class Product1Controller : ControllerBase
简而言之,如何将任何接口的IConfiguration注入到Class Decorator中?
最简单的解决方案是在约束实现内部使用服务定位器模式检索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
与服务定位器一起使用可能会更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.