In this recipe, you will learn how and when to use dependency injection with filters.
We'll understand the IActionFilter
interface, TypeFilter
, and ServiceFilter
attributes by applying a dependency injection into a controller.
- First, let's create an
ActionFilter
class only by deriving fromIActionFilter
:
public class MyActionFilter : IActionFilter { public void OnActionExecuting(ActionExecutingContext context) { // do something before the action executes } public void OnActionExecuted(ActionExecutedContext context) { // do something after the action executes } }
- To use this class as an attribute, we have to use a
TypeFilter
attribute, and give it this class as a parameter. We can't useMyActionFilter
directly as an attribute, because it doesn't inherit fromActionFilterAttribute
:
[TypeFilter(typeof(MyActionFilter))] public IActionResult Index() { return View...