Search code examples
dependency-injectionasp.net-mvc-5autofac

How to inject dependency into MVC 5 global filter using Autofac


I am registering a global filter in MVC5 that takes a dependency on a Migration class:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
   filters.Add(new OfflineActionFilter(new Migration("connectionstring"));
}

I am using Autofac to inject dependencies into my controllers and I would prefer to use dependency injection here too. And I would prefer not to use the service locator (anti)-pattern. How to do this? Property injection in the OfflineActionFilter perhaps? But how?


Solution

  • I found the solution in the documentation under enable property injection for action filters:

    First remove call to filters.Add in the RegisterGlobalFilters method and use Autofac's MVC integration to register the filter instead:

    builder.RegisterFilterProvider();
    builder.Register(c => new OfflineActionFilter()) //parameterless constructor
           .AsActionFilterFor<Controller>()
           .PropertiesAutowired() //using property injection here
           .InstancePerRequest();
    

    Interestingly, while the title of the section in the documentation might make you think we could only use property injection, I found that it also worked with constructor injection (so I went with this solution instead):

    builder.RegisterFilterProvider();    
    builder.Register(c => 
             new OfflineActionFilter(c.Resolve<Migration>()))//constructor with parameter
           .AsActionFilterFor<Controller>()
           .InstancePerRequest();