In Kodein dependency injection, how can you inject instances of Kodein itself into instances?

时光毁灭记忆、已成空白 提交于 2020-01-03 16:56:17

问题


In Kodein, I have modules imported into a parent module, and sometimes the classes need an instance of Kodein so they can do injection themselves later. The problem is this code:

val parentModule = Kodein {
    import(SomeService.module)
}

Where SomeService.module needs the Kodein instance for later, but Kodein isn't yet created. Passing it later into the module seems like a bad idea.

In Kodein 3.x I see there is the kodein-conf module that has a global instance, but I want to avoid the global.

How do other modules or classes get the Kodein instance?

Note: this question is intentionally written and answered by the author (Self-Answered Questions), so that the idiomatic answers to commonly asked Kotlin/Kodein topics are present in SO.


回答1:


In Kodein 3.x (and maybe older versions) you have access to a property within the initialization of any module called kodein that you can use in your bindings.

Within your module, the binding would look like:

bind<SomeService>() with singleton { SomeService(kodein) }

For a complete example and using a separation of interfaces vs. implementation, it might look something like this:

interface SomeService {
   // ...
}

class DefaultSomeService(val kodein: Kodein): SomeService {
    companion object {
        val module = Kodein.Module {
            bind<SomeService>() with singleton { DefaultSomeService(kodein) }
        }
    }

    val mapper: ObjectMapper = kodein.instance()
    // ...
}

You can import the module from the parent as you noted and it will receive its own reference to the current Kodein instance.

val kodein = Kodein {
    import(DefaultSomeService.module)
}


来源:https://stackoverflow.com/questions/38572796/in-kodein-dependency-injection-how-can-you-inject-instances-of-kodein-itself-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!