0

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 ?

sayah imad
  • 1,507
  • 3
  • 16
  • 24
Sathish Guru V
  • 1,417
  • 2
  • 15
  • 39
  • Have you seen the [`ServiceFilterAttribute`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.servicefilterattribute?view=aspnetcore-2.2)? – Silvermind May 27 '19 at 11:26

1 Answers1

3

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.

poke
  • 369,085
  • 72
  • 557
  • 602
  • Thanks Poke. I was fiddling with the DI in the Attribute's Constructor, now I am able to proceed with the your solution. – Sathish Guru V May 28 '19 at 07:23
  • 1
    RE your edit suggestion: `GetService` is not deprecated. You may need to add a using for the `Microsoft.Extensions.DependencyInjection` namespace to make it compile. – poke May 28 '19 at 10:05