IDependencyResolver and Global Action Filters in ASP.Net MVC 3

Following on my previous posts regarding IDependencyResolver and Bootstrapping Unity, I realise that there is a fairly elegant solution to injecting global action filters at runtime.

Multiple ActionFilters can be registered with Unity as follows:

public void Configure(IUnityContainer container){
  container.RegisterType<IActionFilter, MyTracerImpl>("trace");
  container.RegisterType<IActionFilte, MyLoggerImplr>("log");

Then it is simply a matter of using the DependencyResolver to get all the instances of IActionFilter – do this in RegisterGlobalFilters in Global.asax.cs as follows:

public static void RegisterGlobalFilters(GlobalFilterCollection filters){
  filters.Add(new HandleErrorAttribute());

  foreach (IActionFilter filter in DependencyResolver.Current.GetServices<IActionFilter>()){


Make sure that the DependencyResolver is set in Application_Start !!

This entry was posted in ASP.Net MVC, Dependency Injection/Inversion of Control and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s