Global Filters and Dependency Injection in MVC3

by ely August 18, 2011 01:07

I’ve been struggling with finding a good solution to resolve dependencies in global filters lately.  Since it does not appear that global filters are created through the FilterAttributeFilterProvider (I don’t get any results back from base.GetFilters, hit me up if I’m doing something wrong here), my global filters that had resolve attributes on its properties were never being created by the provider, and thus, not getting those properties resolved.

It then dawned on me that the global filters are actually being instantiated in the global.asax.cs file (or wherever your app startup exists at).  So instead of newing up the object directly, I just let Ninject do it for me:

private static void RegisterGlobalFilters(GlobalFilterCollection filters, IKernel kernel)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(kernel.TryGet(typeof(UserProviderFilterAttribute)));
        }

At first this felt like a giant hack, but after awhile I warmed up to it and realized that since this is the area of responsibility for creating global filters, that using Ninject to resolve its dependencies does in fact belong here.

If you have other methods for doing resolving your dependencies in global filters, or if I am way off base, I would love to hear any comments or suggestions.

Tags: ,

mvc

blog comments powered by Disqus

Powered by BlogEngine.NET 2.0.0.36
Theme by Mads Kristensen | Modified by Mooglegiant

About me

@ElyLucas

I am a Denver based software developer, focusing mainly on web technologies in the Microsoft stack.  I dig Asp.Net, MVC, jQuery, C#, JavaScript, and HTML5.  I am starting to dabble in mobile technologies like iOS, Android, and wp7, and have particular interests in mobile web.  I am a Microsoft MVP for Asp.Net/IIS.  I live in Westminster, CO with my wife, son, and dog.  During the day, I sling code for @aspenware creating awesome software.


Month List

Page List

Site hosted by: