Skip to content

Conditional bindings for filters

Breno Vieira edited this page Oct 23, 2015 · 6 revisions

Usually, a filter is applied to a few actions. With the MVC3 extension for Ninject this is done by adding a condition to the filter binding. The available overloads of “When” are a bit different than for other Ninject bindings. Below you find examples of the available When overloads.

// LogFilter is applied to controllers that have the LogAttribute
this.BindHttpFilter<LogFilter>(FilterScope.Controller)
     .WhenControllerHas<LogAttribute>()
     .WithConstructorArgument("logLevel", Level.Info);
 
// LogFilter is applied to actions that have the LogAttribute
this.BindHttpFilter<LogFilter>(FilterScope.Action)
     .WhenActionMethodHas<LogAttribute>()
     .WithConstructorArgument("logLevel", Level.Info);
 
// LogFilter is applied to all actions of the HomeController
this.BindHttpFilter<LogFilter>(FilterScope.Action)
     .WhenControllerTypeIs<HomeController>()
     .WithConstructorArgument("logLevel", Level.Info);
 
// LogFilter is applied to all Index actions
this.BindHttpFilter(FilterScope.Action)
     .When((controllerContext,  actionDescriptor) =>
                actionDescriptor.ActionName == "Index")
     .WithConstructorArgument("logLevel", Level.Info);

Further Information on this topic: