Thursday 6 March 2014

Autofac DI on action filters

Trying to inject a dependency on an action filter in MVC with autofac the other day, property injection seems to be the order of the day. So here's how to do it:

Here's the filter :

public class MyFilter: FilterAttribute, IAuthorizationFilter
{
       public Dependency MyDependency { get;set;}
}

Autofac registrations:

var builder = new ContainerBuilder();
builder.RegisterFilterProvider();
builder.Register<Dependency>(c => new MyConcreteDependency());
builder.RegisterType<MyFilter>().PropertiesAutowired();

note the RegisterFilterProvider line very important.....

Shazaammm !

No comments:

Post a Comment