are multiple ninject bindings guaranteed to maintain their binding order
Asked Answered
C

2

7

If I register:

Bind<IWeapon>().To<Sword>();
Bind<IWeapon>().To<Knife>();
Bind<IWeapon>().To<ChuckNorris>();

And then retrieve via:

IEnumerable<IWeapon> weapons = ServiceLocator.Current.GetAllInstances<IWeapon>();

Am I guaranteed the bindings will always be handed back in that order?

I tried it, and it seems it does, but this could be purely incidental.

Converse answered 21/10, 2011 at 8:31 Comment(0)
W
6

Short answer: No, you aren't!

A bit longer answer: The current implementation keeps the order. But it is not garanteed that this will still be the case in future versions of Ninject. Also you shouldn't have such business rules in the IoC container configuration.

Whimper answered 21/10, 2011 at 9:31 Comment(1)
This seems like a bad decision. Container's setup already contain plenty of logic with method bindings, conditions, names, etc. Ordering dependencies there seems appropriate and natural (and already implemented), as opposed to cooking up a separate mechanism specifically for that.Dogeared
P
0

I found a way to do ordered multi-bindings, because I needed this too:

(admittedly very similar to my answer here: https://mcmap.net/q/775066/-inject-array-of-interfaces-in-ninject)

   // Binding
   public sealed class FooModule: NinjectModule 
   {
     public opverride void Load() 
     {
        Bind<IReadOnlyList<IFoo>>().ToMethod(c=>new IFoo[]
        {
          c.Kernel.Get<FooType1>(),
          c.Kernel.Get<FooType2>(),
           ...
        });
      }
   }

   // Injection target
   public class InjectedClass {
      public InjectedClass(IReadOnlyList<IFoo> foos) { ;}
   }

I agree that just specifying that future versions will preserve the declaration order is a better solution, but this workaround works.

I would have liked to create the child object c within the context c, so Get would know it was being injected into InjectedClass, but I could not figure out how to do that.

Phelia answered 25/5, 2019 at 16:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.