Calling super constructor in C#
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;
}
}
Samantha J T Star
I'm in the Philippines so if you send some comment I may not be able to answer if I am sleeping :-) The good thing is I work all day until late each night.
Updated on August 04, 2022Comments
-
Samantha J T Star almost 2 years
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?
-
Samantha J T Star over 12 yearsI'm sorry. I don't understand your example. What I need is to construct the BaseConstructor and the sequenceService.
-
Samantha J T Star over 12 yearsSaw your comments about DI but already I am using Unity for dependency injection. Can't I do this with Unity? I am wondering how Unity works because already it sets up my AccountController and feeds instances into it. What if I just make a call to the BaseController. Will Unity not catch this and set up the SequenceService automatically?
-
Oded over 12 years@Samantha2 - stackoverflow.com/questions/5329399/…