In Kodein dependency injection, how can you embed Kodein instances in instances?

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

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

Where SomeService.modulea Kodein instance is required for later, but Kodein has not been created yet. Passing it later to the module seems like a bad idea.

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

How do other modules or classes get a Kodein instance?

Note: this question is intentionally written by the author and the author ( Answering Machine ), so the idiomatic answers are usually in the SO section there are Kotlin / Codeine topics.

+4
source share
1 answer

In Kodein 3.x(and possibly older versions), you have access to the property in the initialization of any module with a name kodeinthat you can use in your bindings.

In your module, the binding will look like this:

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

For a complete example and using interface separation and 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 get its own link to the current instance of Kodein.

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

Source: https://habr.com/ru/post/1649054/


All Articles