Why are optional constructor parameters are not considered during dependency resolution

Viewed 110

I have a class that implements ITranslator as below:

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:

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

But another branch (latest) of the same repo did not have this issue. 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.

Just wanted to know if there is a better way to address this.

1 Answers

You need to specify it as an optional param :

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

Related