0

给定一个kodein实例:

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() }
    }
}

有没有办法从 kodein 获取 A、B、C 而不是 D 的实例?

我得到的最接近的是:

val singletonBindings = kodein.container.bindings.filterValues { it is SingletonBinding<*> }
val singletonInstances = singletonBindings.map { it.value.getInstance(???, ???, Unit) }

设置绑定没有什么帮助,因为我无法将单个实例绑定为 set-enabled-type 并且我希望将其绑定为:

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>>()
}

原因Exception in thread "main" java.lang.IllegalStateException: No set binding to bind<Set<out A>>() with ? { ? }

这解决了这个问题,但很丑陋:

  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>>()
4

1 回答 1

2

除了您刚刚所做的之外,Kodein 4 中没有其他方法可以做到这一点。你能在 Kodein 的 GitHub 上开一张票吗?我可能有时间把它挤进 Kodein 5 ;)

于 2018-01-20T13:10:16.647 回答