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?
To explicitly call the superclass constructor from the subclass constructor, we use super() . It's a special form of the super keyword.
Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.
Super class constructor is always called during construction process and it's guaranteed that super class construction is finished before subclass constructor is called. This is the case for most if not all the object oriented language.
To call the parameterized constructor of base class inside the parameterized constructor of sub class, we have to mention it explicitly. The parameterized constructor of base class cannot be called in default constructor of sub class, it should be called in the parameterized constructor of sub class.
You can chain constructors:
public class ProductsController : BaseController
{
public ProductsController(
IService<Account> productService) : base(productService)
{
_product = productService;
}
}
Note that the chained BaseController
(using the base
keyword) has been passed the productService
parameter, tough this can be anything.
Update:
You could do the following (poor mans' dependency injection):
public class ProductsController : BaseController
{
public ProductsController(
IService<Account> productService) : base(new SequenceService())
{
_product = productService;
}
}
Or, pass in the dependency on ISequenceService
through your inheriting types:
public class ProductsController : BaseController
{
public ProductsController(
IService<Account> productService, ISequenceService sequenceService)
: base(sequenceService)
{
_product = productService;
}
}
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