【问题标题】:Android kodein difference between **bind() with** and **bind() from****bind() with** 和 **bind() from** 之间的 Android kodein 区别
【发布时间】:2020-05-26 13:33:02
【问题描述】:

在学习 kodein 时,我经常看到 bind() withbind() 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"))

【问题讨论】:

    标签: android kodein


    【解决方案1】:

    bind&lt;Type&gt;() 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 模式)并且应该只用于非常简单的类型,例如数据类。

    【讨论】:

      【解决方案2】:

      with is TypeBinder 是类型绑定(通过 generic),带有给定的标签和类型(必需)。

      来自

      from is DirectBinder 是与给定标签的直接绑定(不是必需的类型)。它的定义类型取决于工厂类型。

      每个 binder 之间的区别只是类型推断的方式。 因此,您可以在声明模块时使用更高效的 binder。

      【讨论】:

        猜你喜欢
        • 2023-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-02
        • 2020-08-10
        • 2014-11-06
        • 2012-05-20
        相关资源
        最近更新 更多