Using NInject, IEnumerable <T> resolution is not executed when the ctor arg argument is entered, but not when Get <IEnumerable <T>> () is executed

When using NInject, if I configured the binding for IEnumerable, it will work if I directly request IEnumerable, but not if another related object requires IEnumerable. Is it for design?

class Program {
    static void Main(string[] args){
        var k = new StandardKernel();
        k.Bind<IEnumerable<int>>().ToMethod(GetInts);
        k.Bind<IFoo>().To<Foo>(); //Has an IEnumberable<int> constructor arg
        var works = k.Get<IEnumerable<int>>(); //returns the array of ints
        var tst = k.Get<IFoo>(); //Empty integer array is passed in by ninject???
        tst.Get(); //returns an empty integer array????
        return;
    }

    public static int[] GetInts(IContext ctx){
        return new int[] {1,2,3,4,5};
    }
}


public interface IFoo{
    IEnumerable<int> Get();
}


public class Foo : IFoo{
    private int[] _vals;

    public Foo(IEnumerable<int> vals){
        _vals = vals.ToArray();
    }

    public IEnumerable<int> Get(){
        return _vals;
    }
}
+5
source share
1 answer

You see Multi Injection .

You can override it by adding explicit Get to your binding:

k.Bind<IFoo>().To<Foo>()
    .WithConstructorArgument( "vals", ctx=>ctx.Kernel.Get<IEnumerable<int>>());

(Although, if you look at the source, I'm sure you will find a way to block Multi Injection.)

+4
source

All Articles