11

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.

nemesv
  • 138,284
  • 16
  • 416
  • 359
Dylan Vester
  • 2,686
  • 4
  • 29
  • 40

2 Answers2

14

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();
nemesv
  • 138,284
  • 16
  • 416
  • 359
-1

since constructors are not inherited.

Usually, it's possible to call the base constructor as follows:

public DescendantClass ()
  : base() 
{
}
Ivan Nikitin
  • 3,578
  • 27
  • 39
  • The OP would need a constructor with an `IUnitOfWork` parameter. – Gert Arnold Oct 16 '11 at 18:28
  • GertArnold is correct, and I know I can cascade the constructors, but this is what I'm trying to avoid. Thanks. – Dylan Vester Oct 16 '11 at 18:33
  • Have a public constructor like this does nothing unless also wanting to provide a "default constructor" for an object with non-default constructors. The base constructor will automatically be called by the implicit "default constructor". – user2246674 Jun 27 '13 at 03:20