Registering global filters in ASP.Net MVC 4 with Autofac

Suppose we have a custom filter defined as follows:

public class CustomFilterAttribute : ActionFilterAttribute
{
    public MyPropery Property { get; set; }
    ...
}

There’s a new way of registering MVC global filters using AutoFac. First, remove the filter registration from your RegisterGlobalFilters because we will have Autofac handle adding them to our controllers/actions instead of MVC.

Then, register your container as follows:

var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());

builder.RegisterType<MyProperty>().As<IProperty>();

builder.Register(c => new CustomFilterAttribute(c.Resolve<IProperty>()))
                .AsActionFilterFor<Controller>().InstancePerHttpRequest();

builder.RegisterFilterProvider();

IContainer container = builder.Build();

DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

Note that by passing in the Controller class into the extension AsActionFilterFor() we are telling AutoFac to apply this filter to all classes that derive from the Controller class (which, in MVC, is all controllers). Since we are calling AsActionFilterFor() without any arguments, we are also specifying we want to have the filter applied to all actions within the specified controllers. If you want to control the scope of your filter, such as applying it to a specific controller and action, you can use lambda expressions like so:

builder.Register(c => new CustomFilterAttribute(c.Resolve<IProperty>()))
    .AsActionFilterFor<HomeController>(c => c.Index())
    .InstancePerHttpRequest();

If your action takes a parameter, use the default keyword to specify:

builder.Register(c => new CustomFilterAttribute(c.Resolve<IProperty>()))
    .AsActionFilterFor<HomeController>(c => c.Detail(default(int)))
    .InstancePerHttpRequest();

Note that you have to use a different extension method based on what type of filter you are registering, here are the supported filter types:

  • AsActionFilterFor
  • AsAuthorizationFilterFor
  • AsExceptionFilterFor
  • AsResultFilterFor

Leave a Reply