I have classes such as AccountsController, ProductsController etc that all inherit from BaseController. Unity sets up my services as needed. These classes also all require a _sequence service. As it is a common requirement for all classes I would like to code this in the BaseController.
public class AccountsController : BaseController
{
public AccountsController(
IService<Account> accountService) {
_account = accountService;
}
public class ProductsController : BaseController
{
public ProductsController(
IService<Account> productService) {
_product = productService;
}
public class BaseController : Controller
{
public IService<Account> _account;
public IService<Product> _product;
protected ISequenceService _sequence;
public BaseController(
ISequenceService sequenceService) {
_sequence = sequenceService;
}
But how can I do this? Should I set up a call to the BaseController inside the constructors of each of the AccountsController and ProductsController?
You can chain constructors:
Note that the chained
BaseController(using thebasekeyword) has been passed theproductServiceparameter, tough this can be anything.Update:
You could do the following (poor mans’ dependency injection):
Or, pass in the dependency on
ISequenceServicethrough your inheriting types: