Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Contextual bindings with Ninject 2.0

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?

like image 681
Przemaas Avatar asked Mar 24 '10 13:03

Przemaas


1 Answers

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);
}
like image 56
Ian Davis Avatar answered Sep 19 '22 13:09

Ian Davis