【发布时间】:2021-12-18 10:03:16
【问题描述】:
我正在关注this 文档来实现 koin 依赖注入,但它对我没有帮助。我被困在Modules.kt 文件中我不知道如何将数据库的DAO 接口传递给koin 的module 中的Repository 构造函数。
UserEntity.kt
@Entity(tableName = "user_table")
data class UserEntity(...)
UserDao.kt
@Dao
interface UserDao { ... }
UserRepository.kt
class UserRepository(private val userDao: UserDao) {...}
UserViewModel.kt
class UserViewModel(private val repository: UserRepository) : ViewModel() {...}
UserDatabase.kt
@Database(
entities = [UserEntity::class],
version = 1,
exportSchema = false
)
abstract class UserDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
companion object {
@Volatile
private var INSTANCE: UserDatabase? = null
fun getDatabase(context: Context, scope: CoroutineScope): UserDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
UserDatabase::class.java,
"user_data_database"
).build()
INSTANCE = instance
instance
}
}
}
}
Modules.kt 这是 Koin 模块
val appModule = module{
single { UserRepository(get()) }
viewModel { UserViewModel(get()) }
}
【问题讨论】:
-
您需要提供的不仅仅是“它对我没有帮助”——究竟什么对您不起作用?你在哪里卡住了? “这是我所有的代码,告诉我怎么做”不是问题。
-
好的,我正在更新我的问题
-
我更新了问题,但我被困在 Modules.kt 课程中。我不知道如何在 UserRepository 中传递接口
-
“它出错了” - 你得到了什么错误?
-
@RyanM 当我将
private val userViewModel: UserViewModel by viewModels { UserViewModel.UserViewModelFactory((application as MainApplication).repository) }替换为private val userViewModel: UserViewModel by viewModels()时,UserActivity.kt出现错误
标签: android dependency-injection koin