繁体   English   中英

派生类是否总是必须调用默认的基本构造函数?

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

我有以下几点:

    public class BaseController : Controller
    {
        protected ISequenceService _sequence;

        public BaseController()
        {
        }

        [InjectionConstructor]
        public BaseController(ISequenceService sequence)
        {
            _sequence = sequence;
        }


 public class ProductsController : BaseController
    {

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

我一直在尝试我能想到的一切,以使BaseController获得一个称为参数构造函数的参数。 但是,总是调用无参数构造函数。 当我删除无参数构造函数时,出现错误。

父级中是否可以有派生类而没有无参数构造函数? 有什么方法可以配置Unity以调用一个参数构造函数?

必须调用基类构造函数。 在大多数情况下,这意味着调用默认构造函数,如果不使用它,它将隐式为您完成。 您可以使用以下语法指定要调用的构造函数:

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

尝试在不首先初始化基类的情况下构造派生类只是行不通。

实际上,这与Unity无关。 如果您简单地执行以下操作,您将遇到相同的行为:

var prodCont = new ProductsController(accountService, productsService);

这将调用ProductsController 2参数构造函数, 调用BaseController 0参数默认构造函数。

您需要做的是告诉ProductsController构造函数依次通过执行以下操作来调用1-parameter基本构造函数而不是默认构造函数:

public ProductsController(IService<Account> accountService, IService<Product> productService)
    : base(sequenceService)

但是没有将ISequenceService传递给该构造函数以转发给基本构造函数,因此您实际上可能想要:

public ProductsController(IService<Account> accountService,
                          IService<Product> productService,
                          ISequenceService sequenceService)
    : base(sequenceService)

假设ISequenceService也通过Unity映射。

您甚至可以只使用较少的参数构造函数,并使用Method Injection作为参数

public abstract class Base : IBase
>     {
> 
>         private IDep dep;
> 
>         [InjectionMethod]
>         public void Initialize(IDep dep)
>         {
>             if (dep == null) throw new ArgumentNullException("dep");
>             this.dep = dep;
> 
>             OnInitialize();
>         }
> 
>         public dep DepProperty
>         {
>             get
>             {
>                 return dep;
>             }
>         }
>         protected abstract void OnInitialize();
>     }

//now your Derived class Constructor will not be forced to have the IDep Parameter 
class Derived : Base
{
    public Derived()
    {

    }

    protected override void OnInitialize()
    {
        // you can access the baseclass dependency Instance in this override
        object depObject = this.DepProperty;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM