根据ConstructorArgument从Ninject获取不同的对象

本文关键字:对象 获取 ConstructorArgument Ninject 根据 | 更新日期: 2023-09-27 18:12:07

我有以下代码:

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

我想根据myRule中的值得到不同的对象。我怎么做呢?像这样的psedocode

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

根据ConstructorArgument从Ninject获取不同的对象

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

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

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