Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Injecting array of concrete classes always contains a single element #227

Closed
slaneyrw opened this issue Dec 8, 2016 · 3 comments
Closed

Comments

@slaneyrw
Copy link

slaneyrw commented Dec 8, 2016

I'm converting an application from Unity to Ninject but I've hit an issue that I cannot find any doco on.

I have a class that has a constructor parameter that is an Array of a concrete class. Unity will inject an empty array if I haven't explicitly registered named instances.

Ninject, on the other hand, will construct an instance of the concrete and give me an array with 1 element.
At the bottom of https://github.com/ninject/Ninject/wiki/Dependency-Injection-With-Ninject, it states that I should be able to inject 0..n.

Is an empty array only possible with interfaces ?

I cannot change the constructor signature, so is it possible to inject an empty array if no implementations of the concrete type are bound ?

@BrunoJuchli
Copy link
Contributor

With T[], List<T> and IEnumerable<T> multi injection takes precedence. If there is no Bindings for T (like Bind<T>()...) then ninject checks whether T is "self-bindable" (i.E. an instantiatable class), if so, it will create an instance of T.

So if T is an abstract class injecting an empty array is possible, too - because in that case T is not "self-bindable".

Short of making T abstract (or maybe changing it's ctors visibility, if that's possible?) the only remedies i can think of is adapting the binding of X where T[] is injected, either using ToConstructor, ToMethod, ToProvider - or mabe with an argument/parameter. Maybe you could also roll your own IParameter which resolves all the Ts by IResolutionRoot.GetAll.

@slaneyrw
Copy link
Author

Thanks, I'll look at the custom IParameter route

@scott-xu scott-xu self-assigned this Sep 17, 2017
@scott-xu scott-xu added this to the 4.0 milestone Sep 18, 2017
@scott-xu
Copy link
Member

Fixed by bf47cc9

@scott-xu scott-xu modified the milestones: 4.0, 3.3.0 Sep 23, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants