Daniel Cheng
Daniel Cheng

Reputation: 870

Shutting down / Closing Kodein context

Say in my application I maintain a few Kodein contexts and there are some shared resources in the Kodein contexts which I would like to close when the context it belongs to is no longer needed.

Below is a simple illustration of the problem:

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

Ideally there are several properties that should be achieved:

I also considered to retrieve only initialized bindings from kodein.container, but there seems to be no apparent way to do so.

Upvotes: 0

Views: 367

Answers (1)

Related Questions