【问题标题】:Get different object from Ninject depending on ConstructorArgument根据 ConstructorArgument 从 Ninject 获取不同的对象
【发布时间】:2011-10-24 15:05:11
【问题描述】:

我有以下代码:

kernel.Get<IFoo>(new ConstructorArgument("rule", myRule))

我希望根据 myRule 中的值获得不同的对象。我怎么做? 像这样的伪代码

Bind<IFoo>().To<Foo1>().When(x=>x.Parameters[0].Value.Type=="type1")
Bind<IFoo>().To<Foo2>().When(x=>x.Parameters[0].Value.Type=="type2")

其中 Type 是 myRule 的成员

【问题讨论】:

    标签: c# dependency-injection ninject ninject-2


    【解决方案1】:

    访问构造函数参数的类型并不容易。您可能希望改为使用命名绑定或元数据和约束。

    Bind<IFoo>().To<Foo1>().WithMetadata("Type", typeof(MyRule1))
    kernel.Get<IFoo>(m => m.Get<Type>("Type", null) == typeof(myRule), ConstructorArgument("rule", myRule))
    

    但提醒只能从配置访问内核(例如属于该配置的工厂)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 2011-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多