c# – Ninject inject add an element to collection when I create the collection – Education Career Blog

I’m using MVVM light and have set up the binding as following:

class TestModule:NinjectModule
{
    public override void Load()
    {
        Bind<ICollection<Element>>().To<Collection<Element>>();
        Bind<Element>().ToSelf();
    }
}

When I try to get a ICollection I get a collection with ONE element. I expect an exmpty collection.

    var _kernel = new StandardKernel(new TestModule());

    var col = _kernel.Get<ICollection<Element>>();
    Console.WriteLine("Count={0}", col.Count);   //Write "Count=1", Expect "Count=0"

,

This is answered on the Ninject mailing list.

This behavior is expected. When a collection is injected, it will find all bindings
that match the generic parameter and add them to the collection being
injected. If you remove your binding on Element, an empty collection would
be injected.

Another example is given showing what can be done based on this behavior.

Leave a Comment