Kotlin 使用Kodein将对象实例传递给构造函数

Kotlin 使用Kodein将对象实例传递给构造函数,kotlin,kodein,Kotlin,Kodein,我是科特林和科丹的新手。我正在尝试使用Java库,需要将一个单例传递给我的一个构造函数。我不知道如何得到一个实际的实例。因为我需要将一个实例传递给构造函数,所以我认为我需要使用DKodein,这样就不会使用延迟加载了 val kodein: DKodein = Kodein.direct { bind<DataSource>() with singleton { val config = HikariConfig() config.jdbcUr

我是科特林和科丹的新手。我正在尝试使用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()) 
    }
}
val-kodein:DKodein=kodein.direct{
使用singleton绑定(){
val config=HikariConfig()
config.jdbcUrl=“jdbc:postgresql://localhost:5432/mydb"
config.username=“用户名”
config.password=“password”
config.drivercassname=“org.postgresql.Driver”
HikariDataSource(配置)
}
使用singleton绑定(){
//我认为这里的kodein.instance()将提供数据源
//我在上面声明的实例。但是我得到了错误(来自Intellij)
//类型推断失败。应为类型不匹配。
//必需:数据源!
//发现:KodeinProperty
DatabaseContext(kodein.instance())
}
}
有什么简单的方法可以做到这一点吗?还是我走错了方向


谢谢。

在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的初始化块中,必须使用
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
无法在其自身的初始化表达式中访问。
kodein
无法在其自身的初始化表达式中访问。