Reputation: 5948
Given a kodein instance:
interface SharedInterface {}
class A : SharedInterface
class B : SharedInterface
class C : SharedInterface
class D
fun main(args: Array<String>) {
val kodein = Kodein {
bind<A>() with singleton { A() }
bind<B>() with singleton { B() }
bind<C>() with singleton { C() }
bind<D>() with singleton { D() }
}
}
Is there a way to get instances of A, B, C but not D from kodein?
The closest I got was:
val singletonBindings = kodein.container.bindings.filterValues { it is SingletonBinding<*> }
val singletonInstances = singletonBindings.map { it.value.getInstance(???, ???, Unit) }
Set binding was of little help as I was not able to bind single instance as set-enabled-type and the type I want it to be bound as:
interface SharedInterface {}
class A : SharedInterface
class B : SharedInterface
class C : SharedInterface
class D
fun main(args: Array<String>) {
val kodein = Kodein {
bind() from setBinding<SharedInterface>()
bind<A>().inSet() with singleton { A() }
bind<B>().inSet() with singleton { B() }
bind<C>().inSet() with singleton { C() }
bind<D>().inSet() with singleton { D() }
}
val shared = kodein.instance<Set<SharedInterface>>()
}
Causes Exception in thread "main" java.lang.IllegalStateException: No set binding to bind<Set<out A>>() with ? { ? }
This fixes the issue but is ugly:
val kodein = Kodein {
bind() from setBinding<SharedInterface>()
bind<SharedInterface>().inSet() with singleton { instance<A>() }
bind<SharedInterface>().inSet() with singleton { instance<B>() }
bind<SharedInterface>().inSet() with singleton { instance<C>() }
bind<A>() with singleton { A() }
bind<B>() with singleton { B() }
bind<C>() with singleton { C() }
bind<D>() with singleton { D() }
}
val shared = kodein.instance<Set<SharedInterface>>()
Upvotes: 0
Views: 639
Reputation: 9584
There is no way in Kodein 4 to do that other than what you just did. Can you open a ticket on Kodein's GitHub ? I may have time to squeeze that into Kodein 5 ;)
Upvotes: 2