Kotlin 关闭/关闭Kodein上下文
假设在我的应用程序中,我维护了一些Kodein上下文,在Kodein上下文中有一些共享资源,当不再需要它所属的上下文时,我希望关闭这些资源 下面是问题的简单说明:Kotlin 关闭/关闭Kodein上下文,kotlin,kodein,Kotlin,Kodein,假设在我的应用程序中,我维护了一些Kodein上下文,在Kodein上下文中有一些共享资源,当不再需要它所属的上下文时,我希望关闭这些资源 下面是问题的简单说明: class SomeConnectionPool: Closeable { override fun close() { /* some operation */ } } class SomeResource: Closeable { override fun close() { /* some operation
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() }
}
class SomeConnectionPool:可关闭{
重写fun close(){/*某些操作*/}
}
类资源:可关闭{
重写fun close(){/*某些操作*/}
}
类SomeService(val池:SomeConnectionPool){
fun doStuff(){/*某些操作*/}
}
类SomeOtherService(val池:SomeConnectionPool){
fun doOtherStuff(){/*一些操作*/}
}
val kodein=kodein{
使用单例{SomeConnectionPool()}绑定()
使用单例{SomeResource()}绑定()
绑定()和单例{SomeService(instance())}
与singleton{SomeOtherService(instance())}绑定()
}
趣味主线(args:Array){
val服务:kodein.instance()提供的SomeService
service.doStuff()
//这将初始化所有内容,甚至是未使用的绑定
val资源由kodein.allInstances()提供
resources.forEach{it.close()}
}
理想情况下,应实现以下几个特性:
- 仅检索已初始化的可关闭实例并关闭它们
和SomeService
不应负责关闭SomeOtherService
,因为它们没有创建实例。他们也不知道这个游泳池是否还在被其他人使用SomeConnectionPool
我还考虑过只从kodein.container中检索初始化的绑定,但似乎没有明显的方法可以做到这一点。kodein 5.1已经介绍过了 看看: