简体   繁体   中英

are multiple ninject bindings guaranteed to maintain their binding order

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.

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.

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

(admittedly very similar to my answer here: https://stackoverflow.com/a/56306527/50088 )

   // 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM