How to use Action Filters with Injection Dependency in ASP.NET CORE?

I use constructor-based dependency injection everywhere in my ASP.NET CORE application, and I also need to resolve dependencies in my action filters:

 public class MyAttribute : ActionFilterAttribute { public int Limit { get; set; } // some custom parameters passed from Action private ICustomService CustomService { get; } // this must be resolved public MyAttribute() { } public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { // my code ... await next(); } } 

Then in the controller:

 [MyAttribute(Limit = 10)] public IActionResult() { ... 

If I put ICustomService in the constructor, I cannot compile my project. So, how do I fuss about getting instances of an interface in an action filter?

+7
c # asp.net-mvc asp.net-core action-filter
source share
2 answers

If you want to avoid the Locator service pattern, you can use DI by injecting the constructor using TypeFilter .

In your controller use

 [TypeFilter(typeof(MyActionFilterAttribute), Arguments = new object[] {10})] public IActionResult() NiceAction { ... } 

And your ActionFilterAttribute no longer needs to access the service provider instance.

 public class MyActionFilterAttribute : ActionFilterAttribute { public int Limit { get; set; } // some custom parameters passed from Action private ICustomService CustomService { get; } // this must be resolved public MyActionFilterAttribute(ICustomService service, int limit) { CustomService = service; Limit = limit; } public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { await next(); } } 

For me, the annotation [TypeFilter(typeof(MyActionFilterAttribute), Arguments = new object[] {10})] seems uncomfortable. To get a more readable annotation, for example [MyActionFilter(Limit = 10)] , your filter should inherit from TypeFilterAttribute . My answer How do I add a parameter to an action filter in asp.net? shows an example of this approach.

+8
source share

You can use Service Locator :

 public void OnActionExecuting(ActionExecutingContext actionContext) { var service = actionContext.HttpContext.RequestServices.GetService<IService>(); } 

If you want to use constructor injection, use TypeFilter . See How to add a parameter to an action filter in asp.net?

+1
source share

All Articles