Global & Configurable Kodein DI
Introduction
The Configurable DI Plugin gives you :
-
A
ConfigurableDIclass that you can pass around and have different sections of your code configure its bindings. -
A
DI.globalinstance that allows to have "one true" source.
The Configurable DI Plugin is an extension that is not proposed by default, this paradigm is in a separate module.
| Using or not using this is a matter of taste and is neither recommended nor discouraged. |
Install
JVM
Javascript (Gradle)
compile 'org.kodein.di:kodein-di-conf-js:7.0.0'
Do not remove the kodein-generic-js (or kodein-erased-js) dependency.
Both dependencies must be declared.
|
ConfigurableDI
Configuring
You can import modules, extend DI objects, or add bindings inside this ConfigurableDI using addImport, addExtend and addConfig.
fun test() {
val di = ConfigurableDI()
di.addModule(aModule)
di.addExtend(otherDI)
di.addConfig {
bind<Dice>() with provider { RandomDice(0, 5) }
bind<DataSource>() with singleton { SqliteDS.open("path/to/file") }
}
}
The DI underlying instance will effectively be constructed on first retrieval.
Once it is constructed, trying to configure it will throw an IllegalStateException.
|
Retrieving
You can use a ConfigurableDI object like any DI object.
Once you have retrieved the first value with a ConfigurableDI, trying to configure it will throw an IllegalStateException.
|
Mutating
A ConfigurableDI can be mutable.
val di = ConfigurableDI(mutable = true)
|
Using a mutable |
A mutable ConfigurableDI can be configured even after first retrieval.
fun test() {
val di = ConfigurableDI(mutable = true)
di.addModule(aModule)
val ds: DataSource by di.instance()
di.addModule(anotherModule) (1)
}
| 1 | This would have failed if the ConfigurableDI was not mutable. |
You can also use the clear method to remove all bindings.
The god complex: One True DI
Sometimes, you want one static DI for your entire application. E.g. you don’t want to have to hold & pass a DI instance throughout your application.
For these cases, the di-conf module proposes a static DI.global instance.
fun test() {
DI.global.addModule(apiModule)
DI.global.addModule(dbModule)
val ds: DataSource by DI.global.instance()
}
|
Just like any |