【问题标题】:Passing object instance to constructor using Kodein使用 Kodein 将对象实例传递给构造函数
【发布时间】:2018-04-15 00:19:27
【问题描述】:

我是 Kotlin 和 Kodein 的新手。我正在尝试使用 Java 库,并且需要将单例传递给我的一个构造函数。我不知道如何获得一个实际的实例。由于我需要将一个实例传递给构造函数,我相信我需要使用 DKodein,所以没有使用延迟加载?

val kodein: DKodein = Kodein.direct {
    bind<DataSource>() with singleton {
        val config = HikariConfig()
        config.jdbcUrl = "jdbc:postgresql://localhost:5432/mydb"
        config.username = "username"
        config.password = "password"
        config.driverClassName = "org.postgresql.Driver"
        HikariDataSource(config)
    }
    bind<DatabaseContext>() with singleton {
        // I thought kodein.instance() here would provide the DataSource
        // instance I declared above. However I get the error (from Intellij)
        // TypeInference failed. Expected type mismatch.
        // Required: DataSource!
        // Found: KodeinProperty<???>
        DatabaseContext(kodein.instance()) 
    }
}

有没有什么简单的方法可以做到这一点?还是我走错了路?

谢谢。

【问题讨论】:

  • kodein 不能在其自己的初始化表达式中访问。

标签: kotlin kodein


【解决方案1】:

在 Kodein 的初始化块中,您必须使用 instance() 而不使用 kodein.

//use Kodein instead of DKodein
val kodein: Kodein = Kodein {
    bind<DataSource>() with singleton {
        val config = HikariConfig()
        config.jdbcUrl = "jdbc:postgresql://localhost:5432/mydb"
        config.username = "username"
        config.password = "password"
        config.driverClassName = "org.postgresql.Driver"
        HikariDataSource(config)
    }
    bind<DatabaseContext>() with singleton {
        //use instance() without kodein
        //or use dkodein.instance()
        DatabaseContext(instance()) 
    }
}

Kodein 区分DKodeinKodein

  • DKodein 允许直接访问实例。
  • Kodein 通过by 创建委托属性。

Kodein 的初始化块提供了对这两个接口的访问。但dkodein 是默认值。如果您使用kodein.instance(),则使用属性初始值设定项版本。

在初始化块之外,你可以像这样访问DKodein

val datasource: DataSource = kodein.direct.instance()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    相关资源
    最近更新 更多