Ontop of the already available action filters MVC 6 introduces Service filters. The newly introduced Service filters allow you to resolve a filter instance directly from the IoC container.
As the filters are registered in the container they can have a lifetime you control (i.e. singleton or transient) and can also use constructor injection.
The ability to control the lifetime of a filter is something annoyingly missing from previous versions of MVC where you couldn’t have a transient or a per-request filter created. This resulted in a lot of services created manually within the OnActionExecuting
or OnActionExecuted
methods.
A filter can now use constructor injection as below.
public interface ILogFilter { }
public class LogFilter : ActionFilterAttribute, ILogFilter
{
private readonly ILog logger;
public LogFilter(ILog logger)
{
this.logger = logger;
}
public override void OnActionExecuting(ActionExecutingContext actionContext)
{
this.logger.Warning("Log a message...");
}
}
As long as the LogFilter is registered in the IoC container
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<ILog, CustomLog>();
services.AddSingleton<ILogFilter, LogFilter>();
}
It can be included on an action using the ServiceFilter
filter factory attribute.
[ServiceFilter(typeof(ILogFilter))]
public IActionResult Index()
{
return View();
}