ASP.NET Core out-of-the-box supports dependency injection on the action filter level. You have to use constructor injection to inject your dependencies in the actionfilter:
public class SampleActionFilter : ActionFilterAttribute | |
{ | |
private readonly ISampleDependency _sampleDependency; | |
public TestActionFilter(ISampleDependency sampleDependency) | |
{ | |
_sampleDependency = sampleDependency; | |
} | |
public override void OnActionExecuting(ActionExecutingContext context) | |
{ | |
Debug.WriteLine("OnActionExecuting"); | |
} | |
public override void OnActionExecuted(ActionExecutedContext context) | |
{ | |
Debug.WriteLine("OnActionExecuted"); | |
} | |
} |
However now it is no longer possible to simply add the action filter as an attribute on top of your controller or action method. This is because attributes must have their constructor parameters supplied where they are applied. Instead you have to use one of the following attributes:
- TypeFilterAttribute
- ServiceFilterAttribute
The key difference is that TypeFilterAttribute
will find and load the dependencies through DI, and inject them into your action filter.
[TypeFilter(typeof(SampleActionFilterAttribute))] | |
public class HomeController : Controller | |
{ | |
} | |
// or | |
[ServiceFilter(typeof(SampleActionFilterAttribute))] | |
public class HomeController : Controller | |
{ | |
} |
The ServiceFilterAttribute
on the other hand attempts to find the filter from the service collection. This means that you have to register your actionfilter first:
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.AddScoped<SampleFilterAttribute>(); | |
} |