Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity Framework and Multiple Constructors Injection

I have a class as a dependency:

public class Foo {
    public Foo() {
        // default constructor
    }

    public Foo(IMyInterface my) {
    }
}

When I tried to inject it into another class I got error message as

Resolution of the dependency failed ...... InvalidOperationException - The current type, IMyInterface, is an interface and cannot be constructed. Are you missing a type mapping?

I never registered IMyInterface with any concrete type, because I reserve this constructor for other purpose.

With my understanding Unity will try to resolve constructor with least parameters first if not clearily instructing it which one to resolve. So it will try to initialize the default constroctor.

Other than I use InjectionConstructorAttribute, is there a smart way I can tell Unity to ignore the 2nd constructor?

like image 720
hardywang Avatar asked May 06 '26 13:05

hardywang


2 Answers

It's the opposite - Unity will try to resolve a constructor with MOST parameters first. You can use InjectionConstructor attribute over one of your constructors to tell unity to prefer this constructor over others.

like image 165
Wiktor Zychla Avatar answered May 09 '26 01:05

Wiktor Zychla


You can indicate in the configuration that the zero-parameter constructor should be used:

<register type="IFoo" mapTo="Foo">
    <lifetime type="external"/>
    <constructor />
</register>
like image 24
Tim Sylvester Avatar answered May 09 '26 02:05

Tim Sylvester



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!