如何获取一种类型的绑定单例实例列表?

时间:2018-01-20 11:26:21

标签: dependency-injection kotlin kodein

给出一个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>>()

1 个答案:

答案 0 :(得分:2)

除了你刚刚做的事情之外,Kodein 4没有办法做到这一点。 你能在Kodein的GitHub上开票吗? 我可能有时间把它挤进Kodein 5;)