Skip to content

Conditional bindings for filters

Remo Gloor edited this page May 5, 2014 · 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.

```text
// LogFilter is applied to controllers that have the LogAttribute
this.BindHttpFilter(FilterScope.Controller)
     .WhenControllerHas()
     .WithConstructorArgument("logLevel", Level.Info);
 
// LogFilter is applied to actions that have the LogAttribute
this.BindHttpFilter(FilterScope.Action)
     .WhenActionHas()
     .WithConstructorArgument("logLevel", Level.Info);
 
// LogFilter is applied to all actions of the HomeController
this.BindHttpFilter(FilterScope.Action)
     .WhenControllerTypeIs()
     .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:

Clone this wiki locally