与Ninject 2.0的上下文绑定

时间:2010-03-24 13:14:07

标签: parameters ninject ninject-2 conditional-binding contextual-binding

在Ninject 1.0中,我有以下绑定定义:

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

鉴于我有这样的约束:

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

第一次调用被解析为Target1的实例,第二次调用被解析为Target2的实例。

如何将其翻译成Ninject 2.0?

1 个答案:

答案 0 :(得分:6)

您可以使用元数据

[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);
}