如何修复kotlin中的“ [Dagger / MissingBinding]”?

时间:2019-08-01 08:00:13

标签: kotlin dagger

我正在尝试在AppComponent中注入LatestChart,并出现[Dagger / MissingBinding]问题。如果没有@Inject构造函数或@Provides注释的方法,则无法提供LatestChart ... 预先感谢您的帮助

LatestChart.kt


class LatestChart {

    @Inject
    lateinit var context: Context

    @Inject
    lateinit var formatter: YearValueFormatter

    lateinit var chart: LineChart


    init {
        App.appComponent.inject(this)
    }

    fun initChart(chart: LineChart) {
        this.chart = chart

        ***

    }


    fun addEntry(value: Float, date: Float) {
        ***
        }
    }

    private fun createSet(): LineDataSet {
        ***
        }
        return set
    }
}

和AppComponent.kt



@Component(modules = arrayOf(AppModule::class, RestModule::class, MvpModule::class, ChartModule::class))
@Singleton
interface AppComponent {

***

    fun inject(chart: LatestChart)
}

编译错误:

***AppComponent.java:8: error: [Dagger/MissingBinding] sn0w.test.crypto.chart.LatestChart cannot be provided without an @Inject constructor or an @Provides-annotated method. This type supports members injection but cannot be implicitly provided.
public abstract interface AppComponent {
                ^
  A binding with matching key exists in component: sn0w.test.crypto.di.AppComponent
      sn0w.test.crypto.chart.LatestChart is injected at
          sn0w.test.crypto.activities.ChartActivity.latestChart
      sn0w.test.crypto.activities.ChartActivity is injected at
          sn0w.test.crypto.di.AppComponent.inject(sn0w.test.crypto.activities.ChartActivity)



1 个答案:

答案 0 :(得分:1)

您当前尝试将依赖项注入LatestChart的方式是如何满足Dagger不会创建的对象(例如活动)中的依赖项。如果您自己创建LatestChart对象(仅val latestCharts = LatestCharts()),则会看到contextformatter实际上已注入到此新创建的实例中。

但是,如果您希望Dagger将LatestChart对象注入另一个对象(我根据编译错误将其注入ChartActivity中),则必须让Dagger知道如何创建其实例。有两种方法可以实现:

1。用LatestChart

注释@Inject构造函数
class LatestChart @Inject constructor(
    private val context: Context,
    private val formatter: YearValueFormatter
) {
    lateinit var chart: LineChart

    fun initChart(chart: LineChart) { ... }
    fun addEntry(value: Float, date: Float) { ... }
    private fun createSet(): LineDataSet { ... }
}

2。在Dagger模块之一中创建提供者方法

class LatestChart(private val context: Context, private val formatter: YearValueFormatter) {
    lateinit var chart: LineChart

    fun initChart(chart: LineChart) { ... }
    fun addEntry(value: Float, date: Float) { ... }
    private fun createSet(): LineDataSet { ... }
}

@Module
class LatestChartModule {

    @Module
    companion object {
        @JvmStatic
        @Provides
        fun provideLatestChart(context: Context, formatter: YearValueFormatter): LatestChart =
            LatestChart(context, formatter)
    }
}