3
votes

I am new to Ninject and am struggling to get this test to pass. (This test passed with Autofac but the behaviour seems different in Ninject).

[Test]
public void RegisterInstance_unnamed_should_return_unnamed_when_multiple_registrations()
{
    var sut = new StandardKernel();
    var instance1 = new Dependency3();
    var instance2 = new Dependency3();

    sut.Bind<Dependency3>().ToConstant(instance1).Named("instance1");
    sut.Bind<Dependency3>().ToConstant(instance2);

    sut.Get<Dependency3>("instance1").ShouldBeSameAs(instance1);
    sut.Get<Dependency3>().ShouldBeSameAs(instance2);
}

When I call the last line I get this exception message:

Ninject.ActivationException : Error activating Dependency3

No matching bindings are available, and the type is not self-bindable.

Activation path: 1) Request for Dependency3

How do I resolve a binding that is not named when there are multiple bindings?

Thanks

1
Actually i believe the exception that you receive states More than one matching bindings are available. If so please edit the question accordingly. - BatteryBackupUnit
Thanks, but the error message was "No matching bindings." I've updated the question with the exact wording of the exception message. - Michael Whelan
This post might answer your question: stackoverflow.com/questions/5997483/… - CarllDev
What version of ninject are you using? I'm using 3.2.2.0. I've copied your exact test code and the error message i receive is More than one matching bindings are available at line sut.Get<Dependency3>().ShouldBeSameAs(instance2);. I suspect in your actual test code you might have missspelled "instance1" at either Bind or Get. Then it would make sense that you'd get the error No matching bindings are available(...) at sut.Get<Dependency3>("instance1").ShouldBeSameAs(instance1); - BatteryBackupUnit

1 Answers

3
votes

If you want to treat the un-named binding as a "default", you're required to add .BindingConfiguration.IsImplicit = true to the named bindings. Like so:

Bind<Dependency3>().ToConstant(instance1)
   .Named("instance1")
   .BindingConfiguration.IsImplicit = true;

Otherwise the named binding will satisfy a request without a name as well.