我无法通过 Koin DI 从我的项目的构造函数中调用注入。
如果我使用“ ... by inject() ”来注入 DataRepository 类,那么一切都很好。但我想在类的构造函数中提供注入。
我在“ repo.addPayment(payment) ”行的 CounterPresenter 类中发生了崩溃。向下看页面。
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:503)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
Caused by: org.koin.error.NoBeanDefFoundException: No compatible definition found. Check your module definition
这是我的结构:
Koin DI 请问,我怎样才能改变这个模块来成功工作?
val repositoryModule = module {
single { PrefsManager() }
single<IRepository> { DataRepository(get() as LocalRepository) }
single<ILocalRepository> { LocalRepository(get()) }
}
val databaseModule = module {
single {
Room.databaseBuilder(androidApplication(), AppDatabase::class.java, Enviroment.DATABASE_NAME).build()
}
single { get<AppDatabase>().getCounterDao() }
}
val presentersModule = module {
factory { CounterPresenter() }
factory { SplashPresenter() }
}
类数据存储库
class DataRepository(private val localRepository: ILocalRepository) : IRepository {
init { Log.d("ROMAN", "init DataRepository") }
override suspend fun addPayment(payment: Int) {
localRepository.addPayment(payment)
}
}
类 LocalRepository
class LocalRepository(private val counterDao: CounterDao) : ILocalRepository {
override suspend fun addPayment(payment: Int) = runBlocking {
counterDao.insertPayment(Payment(payment))
}
}
类 CounterPresenter
class CounterPresenter : BasePresenter<CounterContract.View>(), CounterContract.Presenter {
private val repo: DataRepository by inject()
override fun onViewCreated() {
super.onViewCreated()
launchIO { repo.addPayment(payment) }
}