c# – Ninject 2.0 – 绑定到多次使用同一接口的对象?
发布时间:2020-12-15 18:14:55 所属栏目:百科 来源:网络整理
导读:考虑以下: public Something(IInterface concreteObjectOne,IInterface concreteObjectTwo) { this.concreteObjectOne = concreteObjectOne; this.concreteObjectTwo = concreteObjectTwo; } 如何设置此类绑定与Ninject?我试着用谷歌搜索这个词,但由于我不
考虑以下:
public Something(IInterface concreteObjectOne,IInterface concreteObjectTwo) { this.concreteObjectOne = concreteObjectOne; this.concreteObjectTwo = concreteObjectTwo; } 如何设置此类绑定与Ninject?我试着用谷歌搜索这个词,但由于我不知道这叫做什么我不能,也无法在Wiki上找到任何关于此的内容. 编辑: 我相信这称为基于约定的绑定,如here所述.但是,此文档适用于版本1.0和2.0没有Only方法.我希望这可以在没有属性的情况下实现 – 使用名称约定或类似的东西. 解决方法
除了使用“仅”方法之外,本文还通过为注入的对象指定不同的属性来提出另一种解决方案.
例: public class ObjectOneAttribute : Attribute { } public class ObjectTwoAttribute : Attribute { } 然后 public Something([ObjectOneAttribute] IInterface concreteObjectOne,[ObjectTwoAttribute] IInterface concreteObjectTwo) { this.concreteObjectOne = concreteObjectOne; this.concreteObjectTwo = concreteObjectTwo; } 当您想要将接口绑定到正确的具体对象时,请使用“WhereTargetHas”方法: Bind<IInterface>().To<YourConcreteTypeOne>().WhereTargetHas<ObjectOneAttribute>(); Bind<IInterface>().To<YourConcreteTypeTwo>().WhereTargetHas<ObjectTwoAttribute>(); 更新:不使用属性的解决方案: Bind<IInterface>().To<YourConcreteTypeOne>().When(r => r.Target.Name == "concreteObjectOne"); Bind<IInterface>().To<YourConcreteTypeTwo>().When(r => r.Target.Name == "concreteObjectTwo") ; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |