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.
There are two base classes for controllers, namely ControllerBase and Controller. The ControllerBase class implements the IController interface and provides the implementation for several methods and properties. It defines an abstract method named ExecuteCore that is used to locate the action method and execute it.
You can take advantage of the ServiceFilter attribute to inject dependencies in your controller or your controller's action methods.
What is Property Dependency Injection in C#? In Property Dependency Injection, we need to supply the dependency object through a public property of the client class. Let us see an example to understand how we can implement the Property or you can say setter dependency injection in C#.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With