How to inject contentResolver with Koin

435 views Asked by At

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.

2

There are 2 answers

1
Bram Stoker On

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

private val module = module {

    single { [email protected] } // tell Koin this is your ContentResolver

    single<MyRepository> {
        MyDataSource(get(), get()) // now Koin knows how to get the content resolver here
    }
}
0
Maciej Beimcik On

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

val module = module {
  // ...

  single<ContentResolver> { androidContext().contentResolver }

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