Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 288
Dylan Vester Avatar asked Oct 16 '11 18:10

Dylan Vester


People also ask

What is the base class for controller?

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.

Can we inject the dependency to individual action method of the controller?

You can take advantage of the ServiceFilter attribute to inject dependencies in your controller or your controller's action methods.

What is Property injection C#?

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#.


1 Answers

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();
like image 143
nemesv Avatar answered Oct 18 '22 20:10

nemesv