如何用Koin注入contentResolver



我正试图在我的数据源类中注入一个带有koin的contentProvider,但我找不到任何方法可以做到这一点。

这是我的数据源

class MyDataSource(private val application: Application, private val contentProvider: ContentResolver) : MyRepository {...}

和我的koin 模块

single<MyRepository> {
MyDataSource(get(), get())
}

我得到了这个错误:

导致原因:org.koin.core.error.NoBeanDefFoundException:未找到"android.content.ContentResolver"的定义。检查模块定义。

告诉Koin如何获得ContentResolver。假设您在自定义Application(比如MyApplication(类中初始化模块:

private val module = module {
single { this@MyApplication.contentResolver } // tell Koin this is your ContentResolver
single<MyRepository> {
MyDataSource(get(), get()) // now Koin knows how to get the content resolver here
}
}

调用androidContext()扩展函数,该函数保存对ContentResolver:的引用

val module = module {
// ...
single<ContentResolver> { androidContext().contentResolver }
single<MyRepository> {
MyDataSource(get(), get())
}
// ...
}

最新更新