【发布时间】:2019-03-29 22:54:35
【问题描述】:
我有以下定义:
@Module
class WeaverDataModule {
// Provide the three pumps from providers
// All of them still explicitly mark 'Pump' as their return type
@Provides @IntoSet fun providesPump(thermosiphon: Thermosiphon) : Pump = thermosiphon
@Provides @IntoSet fun providesAnotherPump(suctionBased: SuctionBased) : Pump = suctionBased
@Provides @IntoSet fun providesGenericPump(genericPump: GenericPump) : Pump = genericPump
}
@Component(modules = [WeaverDataModule::class])
interface WeaverData {
// Get the CoffeeMaker
fun coffeeMaker(): CoffeeMaker
// Get the list of pumps
fun getPumps() : Set<Pump>
}
interface Pump
// The three pumps
class Thermosiphon @Inject constructor(val heater: Heater) : Pump
class SuctionBased @Inject constructor() : Pump
class GenericPump @Inject constructor() : Pump
// Some random heater
class Heater @Inject constructor()
在我的代码中,当我执行以下操作时:
val cm = DaggerWeaverData.builder().build().getPumps()
我确实按预期得到了三个泵。但是,当我尝试将其注入其他类时:
class CoffeeMaker @Inject constructor(
private val heater: Heater,
private val pump: Set<Pump>
) {
fun makeCoffee() =
"Making coffee with heater ${heater::class.java} and using pumps" +
" ${pump.map { it::class.java }.joinToString(",")}"
}
我收到以下错误:
e: .../WeaverData.java:7: error: [Dagger/MissingBinding] java.util.Set<? extends weaver.Pump> cannot be provided without an @Provides-annotated method.
public abstract interface WeaverData {
^
java.util.Set<? extends weaver.Pump> is injected at
weaver.CoffeeMaker(…, pump)
weaver.CoffeeMaker is provided at
weaver.WeaverData.coffeeMaker()
我也尝试过注入Collection<Pump>,但我仍然遇到类似的错误。在dagger docs on multibinding 中,示例(Java 中)显示如下:
class Bar {
@Inject Bar(Set<String> strings) {
assert strings.contains("ABC");
assert strings.contains("DEF");
assert strings.contains("GHI");
}
}
这正是我正在做的。对于基于构造函数的注入,它在 Kotlin 中工作得很好,因为以下编译并按预期运行:
class CoffeeMaker @Inject constructor(
private val heater: Heater
) {
fun makeCoffee() =
"Making coffee with heater ${heater::class.java}"
}
所以我有点不知道如何让这种多重绑定发挥作用。
【问题讨论】: