Reputation: 870
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:
SomeService
and SomeOtherService
should not be responsible of closing SomeConnectionPool
since they did not create the instance. They also do not know whether the pool is still being used by something else.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
Reputation: 9584
Kodein 5.1 has you covered.
Have a look at:
Upvotes: 1