在C调用超级构造函数#
问题描述:
我有类,如AccountsController,ProductsController等都从BaseController继承。 Unity根据需要设置我的服务。这些类也都需要_sequence服务。因为这是所有类的通用要求,所以我想在BaseController中对其进行编码。在C调用超级构造函数#
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;
}
但我该怎么做?我应该在每个AccountsController和ProductsController的构造函数中设置对BaseController的调用吗?
答
你可以连续constructors:
public class ProductsController : BaseController
{
public ProductsController(
IService<Account> productService) : base(productService)
{
_product = productService;
}
}
注意,链接BaseController
(使用base
关键字)已经通过了productService
参数,坚韧这可以是任何东西。
更新:
您可以执行以下操作(差芒依赖注入):
public class ProductsController : BaseController
{
public ProductsController(
IService<Account> productService) : base(new SequenceService())
{
_product = productService;
}
}
或者,通过在ISequenceService
依赖通过你的继承类型:
public class ProductsController : BaseController
{
public ProductsController(
IService<Account> productService, ISequenceService sequenceService)
: base(sequenceService)
{
_product = productService;
}
}
对不起。我不明白你的榜样。我需要的是构建BaseConstructor和sequenceService。 – 2011-12-24 08:19:08
@ Samantha2 - 答案更新了选项。 – Oded 2011-12-24 08:24:45
看到你对DI的评论,但已经使用Unity进行依赖注入。我不能用Unity做这个吗?我想知道Unity是如何工作的,因为它已经建立了我的AccountController并将实例提供给它。如果我只是打电话给BaseController,该怎么办? Unity会不会自动捕获并设置SequenceService? – 2011-12-24 08:25:04