4

We can inject IConfiguration into class like this:

//Controller
AppSettings obj = new AppSettings(_configuration);

//Class
public class AppSettings
{
    private IConfiguration _configuration;

    public AppSettings(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    ...
}

Now I'm trying to inject IConfiguration into my ActionFilter. Whats the best approach to do this?

Shreyas Pednekar
  • 157
  • 1
  • 11

1 Answers1

6

In .NET Core 2.x, IConfiguration is already registered to the DI hence is ready for grab. And normally you would just inject IConfiguration through constructor injection:

public class MyActionFilter : ActionFilterAttribute
{
    private readonly IConfiguration _config;

    public MyActionFilter(IConfiguration config)
    {
        _config = config;
    }
}

That would work but that also means when you use the action filter, you need to supply IConfiguration as one of the parameters:

enter image description here

It would be better if you don't have to provide the dependencies manually.


Use GetService<> instead

One way to go around it is to get the required service(s) on one of the overrides instead:

using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

public class MyActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        var config = context.HttpContext.RequestServices.GetService<IConfiguration>();

        string recaptchaVersion = config.GetValue<string>("recaptcha:version");

        base.OnActionExecuting(context);
    }
}

And if your appsettings.json has something like this:

{
  "recaptcha": {
    "secretKey": "xxx",
    "siteKey": "xxx",
    "version": "v3"
  }
}

Then config.GetValue<> should give you what you want to access

enter image description here

David Liang
  • 16,287
  • 4
  • 37
  • 62
  • The issue you describe is only a problem when using the filter as an attribute. Not all filters are attributes, so generally speaking, there's no problem using constructor injection in filters. Even if you need to use it as an attribute, you can still use `ServiceFilterAttribute` (i.e. `[ServiceFilter(typeof(MyFilterAttribute))]`) – Chris Pratt Sep 19 '19 at 14:46
  • Great example. I was actually working on reCpatcha and saw your response. It was right on the money with the task I was working on to move reCpatcha keys to a filter. – Patrick Mar 22 '20 at 18:31