Samantha J Samantha J - 1 year ago 77
C# Question

Does a derived class always have to call the default base constructor?

I have the following:

public class BaseController : Controller
protected ISequenceService _sequence;

public BaseController()

public BaseController(ISequenceService sequence)
_sequence = sequence;

public class ProductsController : BaseController

public ProductsController(
IService<Account> accountService,
IService<Product> productService
) {
_account = accountService;
_product = productService;

I have been trying everything I can think of to get the BaseController one parameter constructor parameter called. However the parameterless constructor is always called. When I remove the parameterless constructor I get an error.

Is it possible to have a derived class and no parameterless constructor in the parent ? Is there some way that I can configure Unity to call the one parameter constructor?

Answer Source

You must call a constructor of the base class. Most of the time, that means calling the default constructor and if you leave it out, it will be done for you implicitly. You can specify which constructor to call using the following syntax:

public ProductsController(IService<Account> accountService,
                          IService<Product> productService)
    : base((ISequenceService)someISequenceService) // calls the one parameter constructor
                                                   // of the base class

Trying to construct a derived class without initializing the base class first is just not going to work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download