Search code examples
c#asp.net-mvcinversion-of-controlautofac

Property Injection for Base Controller Class


I'm trying to automatically set a property on any controller that derives from my BaseController class. Here is the code in my Application_Start method. The UnitOfWork property is always null when I try and access it.

var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<VesteraTechnologiesContext>().As<IContext>();
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>();
builder.RegisterType<BaseController>()
       .OnActivated(c => c.Instance.UnitOfWork = c.Context.Resolve<IUnitOfWork>());
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

Here is what the BaseController looks like

public class BaseController : Controller
{
    public IUnitOfWork UnitOfWork { get; set; }
}

The reason I'm trying to do this via a property instead on through a constructor is so that I don't have to duplicate the constructor in every controller that needs access to the UnitOfWork property, since constructors are not inherited.


Solution

  • Autofac by default registers the controllers to use constructor injection. To enable property injection with autofac: you should use:

    builder.RegisterControllers(typeof(MvcApplication).Assembly)
           .PropertiesAutowired();