提供具有Dagger多绑定依赖项的实例时出错

时间:2019-01-16 23:51:12

标签: kotlin dagger multibinding

运行以下代码时出现错误。我正在尝试通过D方法将使用Dagger多重绑定构建的地图注入@Provides的实例中。

错误是:

error: [Dagger/MissingBinding] java.util.Map<java.lang.Class<dagger.A>,java.lang.String> cannot be provided without an @Provides-annotated method.
public abstract dagger.D d();
                         ^
  java.util.Map<java.lang.Class<dagger.A>,java.lang.String> is injected at
      dagger.ModuleA.provideD(map)
  dagger.D is provided at
      dagger.ComponentA.d()

代码是:

open class A
class B : A()
class C : A()
data class D(val map: Map<Class<A>, String>)

@Module
object ModuleA {

    @JvmStatic
    @Provides
    @IntoMap()
    @ClassKey(B::class)
    fun provideB(): String {
        return "B"
    }

    @JvmStatic
    @Provides
    @IntoMap()
    @ClassKey(C::class)
    fun provideC(): String {
        return "C"
    }

    @JvmStatic
    @Provides
    fun provideD(map: Map<Class<A>, String>): D {
        return D(map)
    }
}

@Component(modules = [ModuleA::class])
@Singleton
interface ComponentA {
    fun d(): D
}

fun main(args : Array<String>) {
    val dagger = DaggerComponentA.builder().build()
    println(dagger.d())
}

我找不到任何直接的例子。我仅找到使用地图本身的字段注入的示例。

我正在尝试的内容受支持吗?

1 个答案:

答案 0 :(得分:0)

我知道了:

open class A
class B : A()
class C : A()
data class D(val map: Map<Class<out A>, String>)

@MapKey
internal annotation class MyClassKey(val value: KClass<out A>)

@Module
object ModuleA {

    @JvmStatic
    @Provides
    @IntoMap()
    @MyClassKey(B::class)
    fun provideB(): String {
        return "B"
    }

    @JvmStatic
    @Provides
    @IntoMap()
    @MyClassKey(C::class)
    fun provideC(): String {
        return "C"
    }

    @JvmStatic
    @Provides
    @IntoMap()
    @MyClassKey(A::class)
    fun provideA(): String {
        return "A"
    }

    @JvmStatic
    @Provides
    fun provideD(map: Map<Class<out A>, String>): D {
        return D(map)
    }
}

@Component(modules = [ModuleA::class])
@Singleton
interface ComponentA {
    fun d(): D
}

fun main(args : Array<String>) {
    val dagger = DaggerComponentA.builder().build()
    val d = dagger.d()
    println(d.map) // {class dagger.B=B, class dagger.C=C, class dagger.A=A}
}

我需要提供自定义的@MapKey批注:

@MapKey
internal annotation class MyClassKey(val value: KClass<out A>)

然后改变

fun provideD(map: Map<Class<A>, String>): D { 

fun provideD(map: Map<Class<out A>, String>): D {