简体   繁体   English

为什么在依赖解析期间不考虑可选的构造函数参数

[英]Why are optional constructor parameters are not considered during dependency resolution

I have a class that implements ITranslator as below:我有一个实现ITranslator的 class,如下所示:

public SignalTranslator(
 bool compress = false,
 bool validate = false,
 int maxThreads = 2)
{
  // ctor logic
}

I register this implementation as follows:我注册这个实现如下:

Container.RegisterType(typeof(ITranslator), typeof(SignalTranslator));

Since all constructor parameters are optional, shouldn't the service resolution work without any issue?由于所有构造函数参数都是可选的,服务解析不应该没有任何问题吗?

I'm getting the below error during service resolution:我在服务解决期间收到以下错误:

InvalidOperationException: The type Boolean does not have an accessible constructor.

For now, I addressed this issue by having a parameterless ctor as below:现在,我通过一个无参数的ctor解决了这个问题,如下所示:

[InjectionConstructor]
public SignalTranslator()
  : this(false)
{
}

But another branch (latest) of the same repo did not have this issue.但是同一个 repo 的另一个分支(最新)没有这个问题。 I suspect if the newer branch is referring to a more recent version of unity package and the issue I'm facing is part of an older package.我怀疑较新的分支是否指的是更新版本的统一 package 并且我面临的问题是较旧的 package 的一部分。

Just wanted to know if there is a better way to address this.只是想知道是否有更好的方法来解决这个问题。

You need to specify it as an optional param:您需要将其指定为可选参数:

Container.RegisterType(typeof(ITranslator), typeof(SignalTranslator), new OptionalParameter());

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

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