访问 ASP.NET 核心中 Class 装饰器的配置属性
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 装饰器?
最简单的解决方案是在约束实现中使用服务定位器模式来检索 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
可能更容易。
基于此 appsettings.json
.
由于解决方案基于装饰器,我正在寻找一种方法来为装饰器注入 IConfiguration 对象。
示例:
[PortActionConstraint(configuration.GetValue<string>("Product1:Port")]
[Route("api/[controller]")]
[ApiController]
public class Product1Controller : ControllerBase
简而言之,如何将任何接口的 IConfiguration 注入 Class 装饰器?
最简单的解决方案是在约束实现中使用服务定位器模式来检索 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
可能更容易。