在研究kodein时,我经常看到bind()使用,bind()来自。
有谁能告诉我有什么区别吗?为什么我们要用它。
例如:
bind<Dice>() with provider { RandomDice(0, 5) }
bind<DataSource>() with singleton { SqliteDS.open("path/to/file") } bind() from singleton { RandomDice(6) }
bind("DnD20") from provider { RandomDice(20) }
bind() from instance(SqliteDataSource.open("path/to/file"))发布于 2020-02-16 13:54:24
bind<Type>() with显式地定义了Type 。例如,当您将接口类型绑定到它的实现时,这一点很重要:
bind<Type>() with singleton { TypeImpl() }现在考虑绑定一个非常简单的类型,例如配置数据对象:
bind<Config>() with singleton { Config("my", "config", "values") }您已经编写了两次Config:一次在绑定定义中,一次在绑定本身中。
输入bind() from:它不定义类型,但将绑定类型的选择留给绑定本身。绑定类型定义为隐式。例如,您可以这样编写Config绑定:
bind() from singleton { Config("my", "config", "values") }请注意,将类型绑定到自身(这就是bind() from的作用)通常是个坏主意(它违背了IoC模式),应该只用于非常简单的类型,比如数据类。
发布于 2020-02-11 07:58:40
使用
使用is,TypeBinder是类型绑定(通过泛型)与给定标记&类型(是必需的)。
从…
from is DirectBinder是与给定的标记直接绑定(不是必需的类型)。它将被定义类型依赖于类型的工厂.
每个绑定器之间的差异只是类型推断的方式。因此,您可以在声明模块时使用更有效的绑定器。
。
https://stackoverflow.com/questions/60163838
复制相似问题