implementation 'org.kodein.di:kodein-di-generic-jvm:6.3.3'
implementation 'org.kodein.di:kodein-di-framework-android-x:6.3.3'
to create a dependency it is required to provide the builder method for that so that Kodein can create it. in this case lets say we want a Repository with a application context.
class Repository(var application: Application) {
}
the created builders are required to bind to kodein instance in application class.
binding can be done mainly in two ways -
- with singleton - here only single instance for that dependency will be created.
- with provides - here new instances will be created as we required the depdndency over the application.
there anr many other types of binding on kodein which you can have look at the official docs.
class ApplicationClass : Application(), KodeinAware {
private val repositoryModule = Kodein.Module(
"repositoryModule",
allowSilentOverride = true
) {
import(androidXModule(this@ApplicationClass))
bind<Repository>() with singleton { Repository(instance()) }
}
override val kodein: Kodein = Kodein.lazy {
import(repositoryModule)
bind() from provider { SplashViewModelProvider(instance()) }
}
}
this is done in application class so that the kodein instance is accessible all over the application. also do not forget to all this class to menifest as application class.
there are again two ways to get the depdndencies where required.
- injection
- retrival
- injection gives a easy and non kodein dependent way to inject the required depdedencies. but have less features than the retrival method.
- retrival gives us more features but it has the kodein code dependency and you need to get the kodein object inorder to get the required depdedencies.
lets say this is the class that require instanciation -
class Presenter(private val db: Database, private val rnd: Random) {
}
so we have to create its object like this -
val presenter by kodein.newInstance { Presenter(instance(), instance()) }
Here we need the kodein instance in the class from the application class to create the dependencies -
class Presenter(val kodein: Kodein) {
private val db: Database by kodein.instance()
private val rnd: Random by kodein.instance()
}
we can implement the kodeinaware interface to get the kodein instance lazily injected -
class Presenter(): KodeinAware {
override val kodein by lazy { (application as ApplicationClass).kodein }
//or you can do - override val kodein by org.kodein.di.android.kodein()
private val db: Database by instance()
private val rnd: Random by instance()
}