O
O
Orbit
Search…
dependency-injection
By default, Orbit will instantiate and activate Addressables using the default, empty constructor. Many times an Addressable will require some service or store for activation or its functional use.
Orbit supports a "bring your own DI container" model
The typical approach is to use constructor dependency injection, where dependencies are be supplied as constructor arguments.
1
class PlayerImpl(private val playerStore: PlayerStore) : AbstractActor(), Player {
2
... PlayerImpl code
3
}
Copied!
To wire a DI container into Orbit, the addressableConstructor member of OrbitConfig can be replaced with a custom implementation of the AddressableConstructor interface. Below is an example
1
class KodeinAddressableConstructor(private val kodein: Kodein) : AddressableConstructor {
2
object KodeinAddressableConstructorSingleton : ExternallyConfigured<AddressableConstructor> {
3
override val instanceType = KodeinAddressableConstructor::class.java
4
}
5
6
override fun constructAddressable(clazz: Class<out Addressable>): Addressable {
7
val addressable: Addressable by kodein.Instance(TT(clazz))
8
9
return addressable
10
}
11
}
Copied!
In this case, the KodeinAddressableConstructor requires a Kodein instance in its constructor. The instance can be supplied to the internal Orbit container through the containerOverrides member of OrbitConfig which will supply it automatically when the KodeinAddressableConstructor is created.
1
import orbit.carnival.actors.PlayerImpl
2
import orbit.carnival.actors.repository.PlayerStore
3
import orbit.carnival.actors.repository.etcd.EtcdPlayerStore
4
import org.kodein.di.*
5
import org.kodein.di.generic.*
6
7
fun main() {
8
runBlocking {
9
...
10
val kodein = Kodein {
11
bind<PlayerStore>() with singleton { EtcdPlayerStore(storeUrl) }
12
bind<PlayerImpl>() with provider { PlayerImpl(instance()) }
13
}
14
15
val orbitClient = OrbitClient(
16
OrbitClientConfig(
17
...
18
addressableConstructor = KodeinAddressableConstructor.KodeinAddressableConstructorSingleton,
19
containerOverrides = {
20
instance(kodein)
21
}
22
)
23
)
24
...
25
}
26
}
Copied!
Last modified 1yr ago
Copy link