简体   繁体   English

将 2 个类绑定到同一个接口

[英]Binding to 2 classes to the same interface

I have an interface interfaceA, classes classA and classB.我有一个接口interfaceA,类classA和classB。 classA implements interfaceA, classB implements interfaceA.类A实现接口A,类B实现接口A。 classA has business logic and classB is a mocker used for testing purpose. classA 具有业务逻辑,而 classB 是用于测试目的的模拟程序。 I want to bind我要绑定

 bind(interfaceA.class).to(classA.class).in(Singleton.class);
 bind(interfaceA.class).to(classB.class).in(Singleton.class);

In essence, I always want logic in classA to always be used whenever any method of interface is called and classB to be used for testing the classA implementation.本质上,我总是希望在调用任何接口方法时始终使用 classA 中的逻辑,并将 classB 用于测试 classA 实现。

But when I bind it in the above fashion, I get an error complaining a binding is already defined, can't define binding again for interfaceA.但是当我以上述方式绑定它时,我收到一个错误,抱怨绑定已经定义,无法再次为 interfaceA 定义绑定。 How do I effectively solve this?我如何有效地解决这个问题?

Don't bind both at once.不要同时绑定两者。

In your test configuration, bind the test version and in your production one, bind the real implementation.在您的测试配置中,绑定测试版本,在您的生产版本中,绑定真正的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM