7

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?

Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
Przemaas
  • 841
  • 11
  • 23
  • I'll take a look, soon, but you should really be using the mailing list for this stuff. – Ian Davis Mar 24 '10 at 13:37
  • Thanks for pointing this. I didn't know about mailing list. I reposted this question there. – Przemaas Mar 24 '10 at 13:45
  • 4
    @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 Mar 24 '10 at 15:00
  • 1
    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 Mar 24 '10 at 15:04
  • 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 Mar 24 '10 at 16:07
  • OK, maybe I'm wrong then. I used NI1 in depth until about 9 months ago. Will be commencing in depth usage of NI2 in a few days so see you on the mailing list! Thanks for your response and work on NI in general. – Ruben Bartelink Mar 24 '10 at 18:56

1 Answers1

6

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);
}
Ian Davis
  • 3,848
  • 1
  • 24
  • 30