Configurable Action Filter Provider

Wednesday, January 19, 2011

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());

In the next post we'll combine the filter provider with Ninject to take advantage of MVC 3's new dependency resolution features.


Comments
gravatar Nick Thursday, January 20, 2011
Not seen this custom provider before. Good to know it is there but have no thoughts how I could use it yet.
gravatar Paulo Morgado Thursday, January 20, 2011
I love LINQ!!!

return from FilterAction filter in FiltersSettings.Settings.Filters
let filterType = Type.GetType(filter.Type)
select new Filter(
Activator.CreateInstance(filterType),
FilterScope.Global,
order:null);
gravatar scott Friday, January 21, 2011
Oh, @Paulo, why didn't I think of that? :)
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!