【问题标题】:How to get a list of bound singleton instances of one type?如何获取一种类型的绑定单例实例列表?
【发布时间】:2018-01-20 11:26:20
【问题描述】:

给定一个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&lt;Set&lt;out A&gt;&gt;() 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>>()

【问题讨论】:

    标签: dependency-injection kotlin kodein


    【解决方案1】:

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

    【讨论】:

    • 您能分享一下这个设计决定忽略 Kodein 中的子类/接口多态性的原因是什么?
    • 这是在 v5 中发布的吗?
    猜你喜欢
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    • 2013-06-17
    • 2012-12-30
    相关资源
    最近更新 更多