Contextual bindings with Ninject 2.0
Asked Answered
B

1

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?

Baseline answered 24/3, 2010 at 13:14 Comment(6)
I'll take a look, soon, but you should really be using the mailing list for this stuff.Ragman
Thanks for pointing this. I didn't know about mailing list. I reposted this question there.Baseline
@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.Harrier
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.Harrier
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.Ragman
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.Harrier
R
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);
}
Ragman answered 24/3, 2010 at 16:6 Comment(2)
What about when you really need the predicate to live in the Module instead of at the Get call site?Atabrine
You can use the kernel.Bind<IWeapon>().To<Sword>().When*(...) methodsRagman

© 2022 - 2024 — McMap. All rights reserved.