【问题标题】:Shutting down / Closing Kodein context关闭/关闭 Kodein 上下文
【发布时间】:2018-06-21 16:13:45
【问题描述】:

假设在我的应用程序中,我维护了一些 Kodein 上下文,并且 Kodein 上下文中有一些共享资源,当不再需要它所属的上下文时,我想关闭这些资源。

下面是问题的简单说明:

class SomeConnectionPool: Closeable {
    override fun close() { /* some operation */ }
}

class SomeResource: Closeable {
    override fun close() { /* some operation */ }
}

class SomeService(val pool: SomeConnectionPool) {
    fun doStuff() { /* some operation */ }
}

class SomeOtherService(val pool: SomeConnectionPool) {
    fun doOtherStuff() { /* some operation */ }
}

val kodein = Kodein {
    bind<SomeConnectionPool>() with singleton { SomeConnectionPool() }
    bind<SomeResource>() with singleton { SomeResource() }

    bind<SomeService>() with singleton { SomeService(instance()) }
    bind<SomeOtherService>() with singleton { SomeOtherService(instance()) }
}

fun main(args: Array<String>) {
    val service: SomeService by kodein.instance()
    service.doStuff()

    // this will initialize everything even the unused bindings
    val resources by kodein.allInstances<Closeable>()
    resources.forEach { it.close() }
}

理想情况下应该实现几个属性:

  • 仅检索已初始化的 Closeable 实例并关闭它们
  • SomeServiceSomeOtherService 不应该负责关闭 SomeConnectionPool,因为他们没有创建实例。他们也不知道该池是否仍在被其他东西使用。

我也考虑过只从 kodein.container 中检索已初始化的绑定,但似乎没有明显的方法可以这样做。

【问题讨论】:

    标签: kotlin kodein


    【解决方案1】:
    猜你喜欢
    • 2020-12-22
    • 2012-01-01
    • 2015-04-24
    • 2013-07-23
    • 2020-07-18
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多