In Kodein dependency injection, how can you inject

2019-06-25 01:24发布

问题:

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