Search code examples
c#asp.net-web-apiasp.net-coredependency-injectionasp.net-core-2.2

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. These URLs are configured in appsettings.json.

As the solution is based on the Decorators, I am searching for a way to inject the IConfiguration object for the decorators.

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 ?


Solution

  • The easiest solution for this is to use the service locator pattern inside of your constraint implementation to retrieve the IConfiguration object.

    So within the ´IsValidForRequest` method, retrieve the service through the HTTP context:

    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. This will require you to implement the IActionConstraint yourself though. So for this simple requirement, using the ActionMethodSelectorAttribute with the service locator is probably easier.