在研究 kodein 时,我经常看到 bind() with 和 bind() from。
谁能告诉我有什么区别以及我们为什么要使用它。
例如:
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"))
最佳答案
bind<Type>() with
定义 Type
明确地。例如,当您将接口(interface)类型绑定(bind)到它的实现时,这一点很重要:
bind<Type>() with singleton { TypeImpl() }
现在考虑您正在绑定(bind)一个非常简单的类型,例如配置数据对象:
bind<Config>() with singleton { Config("my", "config", "values") }
你写了Config
两次:一次在绑定(bind)定义中,一次在绑定(bind)本身中。
输入 bind() from
:它不定义类型,而是将绑定(bind)类型的选择留给绑定(bind)本身。绑定(bind)类型是隐式定义的。例如,您可以编写 Config
这样的绑定(bind):
bind() from singleton { Config("my", "config", "values") }
请注意,将类型绑定(bind)到自身(这就是 bind() from
的用途)通常不是一个好主意(它违反了 IoC 模式)并且应该只用于非常简单的类型,例如数据类。
关于Android kodein **bind() with** 和 **bind() from** 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60163838/