在C#中调用超级构造函数

时间:2011-12-24 08:03:32

标签: c# asp.net-mvc unity-container

我有一些类,如AccountsController,ProductsController等,都是从BaseController继承的。 Unity根据需要设置我的服务。这些类也都需要_sequence服务。因为这是所有类的常见要求,我想在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;
    }

但我怎么能这样做?我应该在每个AccountsController和ProductsController的构造函数中设置对BaseController的调用吗?

1 个答案:

答案 0 :(得分:12)

您可以链接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;
    }
}