Kotlin “如何修复”;[匕首/缺少装订]”;在科特林?
我正在尝试在AppComponent中注入LatestChart,并使用[Dagger/MissingBinding]解决问题。如果没有@inject构造函数或@Provides注释方法,则无法提供LatestChart。。。 提前谢谢你的帮助 最新图表.ktKotlin “如何修复”;[匕首/缺少装订]”;在科特林?,kotlin,dagger,Kotlin,Dagger,我正在尝试在AppComponent中注入LatestChart,并使用[Dagger/MissingBinding]解决问题。如果没有@inject构造函数或@Provides注释方法,则无法提供LatestChart。。。 提前谢谢你的帮助 最新图表.kt class LatestChart { @Inject lateinit var context: Context @Inject lateinit var formatter: YearValueF
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)
您当前尝试将依赖项注入最新图表的方式是如何满足不会由Dagger创建的对象(例如活动)中的依赖项。如果您自己创建
LatestChart
对象(只是val latestCharts=latestCharts()
),您将看到上下文
和格式化程序
实际上被注入到这个新创建的实例中
但是,如果您希望Dagger将一个LatestChart
对象注入另一个对象(根据编译错误,我假设是注入到ChartActivity
中),则必须让Dagger知道如何创建其实例。有两种方法可以实现这一目标:
1。用@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)
}
}