在Kodein依赖项注入中,如何将Kodein本身的实例注入实例? [英] In Kodein dependency injection, how can you inject instances of Kodein itself into instances?

查看:232
本文介绍了在Kodein依赖项注入中,如何将Kodein本身的实例注入实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Kodein中,我将模块导入到父模块中,有时这些类需要Kodein的实例,以便以后可以自己进行注入.问题是此代码:

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

SomeService.module在以后需要Kodein实例的地方,但尚未创建Kodein.稍后将其传递到模块中似乎是个坏主意.

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.

在Kodein 3.x中,我看到有一个具有全局实例的kodein-conf模块,但是我想避免使用全局实例.

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

其他模块或类如何获取Kodein实例?

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.

推荐答案

在Kodein 3.x(可能是较旧的版本)中,您可以在名为kodein的任何模块的初始化中访问一个属性,该模块可以在绑定.

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()
    // ...
}

您可以按照上面提到的从父级导入模块,它会收到自己对当前Kodein实例的引用.

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

这篇关于在Kodein依赖项注入中,如何将Kodein本身的实例注入实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆