I’ve get a base class like so…
public class BaseController : Controller
{
private readonly IUserRepository userRepository;
public BaseController(IUserRepository userRepository)
{
this.userRepository = userRepository;
}
}
I want all of my MVC controllers to inherit from this class. Is there some way that I can avoid having to supply the ‘userRepository’ instance to the base class from every sub-classes constructor like this?
public HomeController(IUserRepository repository) : base(repository)
{
}
Cheers, Ian.
I think I’ve got it… when registering the contollers for the IoC Container, check whether they inherit from the base class and then if so add some property injection to the mapping. Voila!
I’ve since pondered though as to whether this is a bad design. Yes it saves some typing and makes things look simpler but its opening up some possibly significant side effects into a sub-classes operations. i.e. the sub-class is dependent on objects that haven’t come via the constructor or via method parameters. They may or may not even be there.