[英]Accessing Configuration Properties for the Class Decorators in ASP.NET Core
Based on this Question Here , I am working on the solution to bind the controllers to certain URLs . 基于此问题 ,我正在研究将控制器绑定到某些URL的解决方案。 These URLs are configured in
appsettings.json
. 这些URL在
appsettings.json
中配置。
As the solution is based on the Decorators, I am searching for a way to inject the IConfiguration object for the decorators. 由于该解决方案基于装饰器,因此我正在寻找一种为装饰器注入IConfiguration对象的方法。
Example : 范例:
[PortActionConstraint(configuration.GetValue<string>("Product1:Port")]
[Route("api/[controller]")]
[ApiController]
public class Product1Controller : ControllerBase
In short, how can I inject IConfiguration of any Interface to the Class Decorator ? 简而言之,如何将任何接口的IConfiguration注入到Class Decorator中?
The easiest solution for this is to use the service locator pattern inside of your constraint implementation to retrieve the IConfiguration
object. 最简单的解决方案是在约束实现内部使用服务定位器模式检索
IConfiguration
对象。
So within the ´IsValidForRequest` method, retrieve the service through the HTTP context: 因此,在“ IsValidForRequest”方法中,通过HTTP上下文检索服务:
public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
{
var configuration = routeContext.HttpContext.RequestServices.GetService<IConfiguration>();
// do something with the configuration
}
Alternatively, you could also implement the IActionConstraintFactory
which would allow you to properly resolve the dependencies using constructor injection. 另外,您也可以实现
IActionConstraintFactory
,它允许您使用构造函数注入来正确解析依赖项。 This will require you to implement the IActionConstraint
yourself though. 不过,这将需要您自己实现
IActionConstraint
。 So for this simple requirement, using the ActionMethodSelectorAttribute
with the service locator is probably easier. 因此,对于此简单要求,将
ActionMethodSelectorAttribute
与服务定位器一起使用可能会更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.