匕首2:当父母和孩子都具有相同的注入特征时缺少提供者?

问题描述 投票:0回答:1

我正在使用Dagger 2.24。当我编译以下内容

fun main() {
    val myClass = MyClass()
}

class MyClass {
    @Inject
    lateinit var stringMe: String

    init {
        DaggerMyComponent.create().subComponent().inject(this)
        println(stringMe)
    }
}

@Component
interface MyComponent {
    fun subComponent(): MySubcomponent
    fun inject(a: MyClass)
}

@Subcomponent(modules = [MeSubModule::class])
interface MySubcomponent {
    fun inject(a: MyClass)
}

@Module
class MeSubModule {
    @Provides
    fun stringMe(): String = "Hi here"
}

错误指出

error: [Dagger/MissingBinding] java.lang.String cannot be provided without an @Inject constructor or an @Provides-annotated method.
public abstract interface MyComponent {
                ^
  A binding with matching key exists in component: com.elyeproj.modular1bottombase.MySubcomponent
      java.lang.String is injected at
          com.elyeproj.modular1bottombase.MyClass.stringMe
      com.elyeproj.modular1bottombase.MyClass is injected at
          com.elyeproj.modular1bottombase.MyComponent.inject(com.elyeproj.modular1bottombase.MyClass)   

然后,我注释掉下面的简单行,全部编译正常。

fun main() {
    val myClass = MyClass()
}

class MyClass {
    @Inject
    lateinit var stringMe: String

    init {
        DaggerMyComponent.create().subComponent().inject(this)
        println(stringMe)
    }
}

@Component
interface MyComponent {
    fun subComponent(): MySubcomponent
//    fun inject(a: MyClass)  // Comment this out.
}

@Subcomponent(modules = [MeSubModule::class])
interface MySubcomponent {
    fun inject(a: MyClass)
}

@Module
class MeSubModule {
    @Provides
    fun stringMe(): String = "Hi here"
}

怀疑这是Dagger 2的错误,但是如果我错过任何事情,就在这里写?

android dagger-2
1个回答
0
投票

显然,只要在inject(a: MyClass)中具有以下MyComponent,在编译时,它将尝试验证MyComponent是否能够满足@Inject所需的所有MyClass依赖项。

@Component
interface MyComponent {
    fun subComponent(): MySubcomponent
    fun inject(a: MyClass)  // Comment this out.
}

在上述情况下,MyClass需要String,但是MyComponent本身不具备提供String的能力。所以失败了。当前的注释编译会进行检查,并且实际上是否存在wired up都没有关系。

© www.soinside.com 2019 - 2024. All rights reserved.