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

Sam*_*tar 7 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;
    }
Run Code Online (Sandbox Code Playgroud)

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

Ode*_*ded 12

你可以链构造函数:

public class ProductsController : BaseController
{
    public ProductsController(
        IService<Account> productService) : base(productService)
    {
        _product = productService;
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,链接BaseController(使用base关键字)已经传递了productService参数,艰难的这可以是任何东西.

更新:

可以执行以下操作(穷人的依赖注入):

public class ProductsController : BaseController
{
    public ProductsController(
        IService<Account> productService) : base(new SequenceService())
    {
        _product = productService;
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,通过ISequenceService继承类型传递依赖关系:

public class ProductsController : BaseController
{
    public ProductsController(
        IService<Account> productService, ISequenceService sequenceService) 
        : base(sequenceService)
    {
        _product = productService;
    }
}
Run Code Online (Sandbox Code Playgroud)