7
votes

In Ninject 1.0 I had following binding definitions:

Bind<ITarget>().To<Target1>().Only(When.Context.Variable("variable").EqualTo(true));
Bind<ITarget>().To<Target2>();

Given such bindings I had calls:

ITarget target = kernel.Get<ITarget>(With.Parameters.ContextVariable("variable", true));
ITarget target = kernel.Get<ITarget>(With.Parameters.ContextVariable("variable", false));

First call was resolved to instance of Target1, second call was resolved to instance of Target2.

How to translate this into Ninject 2.0?

1
I'll take a look, soon, but you should really be using the mailing list for this stuff. - Ian Davis
Thanks for pointing this. I didn't know about mailing list. I reposted this question there. - Przemaas
@Ian Davis: I really prefer SO to mailing lists. If the 101 questions can be up here as reorderable, editable, commentable answers rather than burried in a snowdrift of emails, its just better. But that's just me I guess. - Ruben Bartelink
Mailing lists are fine for committers and devotees, but if you want a consumer community, you seed that with docs and then each different stating of the same 101 question can be coalesced there (here). If the committers then want to harvest the chatter contained in the user questions, its in a much more condensed format ready to go and they havent been swamped by neverending torrents of newbies asking the same questions. - Ruben Bartelink
The mailing list has hundreds of people directly interested in the topic making is faster to solve. I love SO for many things, but not for OS projects with followings. - Ian Davis

1 Answers

6
votes

You can use metadata,

[Fact]
public void MetadataBindingExample()
{
    string metaDataKey = "key";
    kernel.Bind<IWeapon>().To<Shuriken>().WithMetadata(metaDataKey, true);
    kernel.Bind<IWeapon>().To<Sword>().WithMetadata(metaDataKey, false);
    kernel.Bind<IWeapon>().To<Knife>();

    var weapon = kernel.Get<IWeapon>(metadata => metadata.Has(metaDataKey) && metadata.Get<bool>(metaDataKey));
    Assert.IsType<Shuriken>( weapon );

    weapon = kernel.Get<IWeapon>(metadata => metadata.Has(metaDataKey) && !metadata.Get<bool>(metaDataKey));
    Assert.IsType<Sword>(weapon);

    weapon = kernel.Get<IWeapon>(metadata => !metadata.Has(metaDataKey));
    Assert.IsType<Knife>(weapon);
}