简体   繁体   中英

How to inject contentResolver with Koin

I'm trying to inject a contentProvider with koin in my datasource class, but I can't find any approach to can do it.

This is my dataSource

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

and my module of koin

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

And I'm getting this error:

Caused by: org.koin.core.error.NoBeanDefFoundException: No definition found for 'android.content.ContentResolver' has been found. Check your module definitions.

Tell Koin how to obtain a ContentResolver . Assuming you intialize your module in your custom Application (say MyApplication ) class:

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
    }
}

Call androidContext() extension function that holds reference to ContentResolver :

val module = module {
  // ...

  single<ContentResolver> { androidContext().contentResolver }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM