August 23, 2011 04:49 by
Scott
In MVC 3 you can implement an IFilterProvider to create and feed action filters to the MVC runtime. Assuming you have the configuration classes in place from the last post, you can create a custom filter provider to add action filters to the MVC pipeline.
public class ConfiguredFilterProvider : IfilterProvider
{
public IEnumerable<Filter> GetFilters(
ControllerContext controllerContext,
ActionDescriptor actionDescriptor)
{
var filters = FiltersSettings.Settings.Filters;
foreach (var filter in filters.Cast<FilterAction>())
{
var filterType = Type.GetType(filter.Type);
yield return new Filter(
Activator.CreateInstance(filterType),
FilterScope.Global, order:null
);
}
}
}
Notice a filter provider receives context parameters it can use to determine if it should create a filter, or not. In this case we are creating global filters from whatever we find in the web.config file, so the parameters are left untouched.
To plug your filter provider into the MVC runtime, you'll need to execute a bit of code during application start up:
FilterProviders.Providers.Add(new ConfiguredFilterProvider());