考虑以下注射器:
class Injector constructor(secretSauce: SecretSauce) {
val kodein = Kodein {
bind<SpicyBeans>() with factory { beans: List<Bean>, herbs: List<Herb> ->
SpicyBeans(secretSauce, beans, herbs)
}
}
}
以及以下业务逻辑:
class TastyMeal {
private lateinit var injector : Kodein
private lateinit var spicyBeans : SpicyBeans
fun initialiseWithInjector(kodein : Kodein) {
injector = kodein
val herbs = listOf(Coriander(), Cumin())
val beans = listOf(Pinto(), BlackEyed())
// fetch SpicyBeans via given Kodein Factory, given herbs and beans here
}
}
如何使用Kodein的直接注入功能通过工厂获取SpicyBeans
实例,并在{em> List<Herb>
之后传入List<Bean>
和TastyMeal
被实例化?我在文档中找不到示例。
答案 0 :(得分:3)
该解决方案称为多参数工厂。 关于此的文档非常稀少(这是一个问题,您可以打开一个票证以便提醒我改进文档吗?)。
同时,这是您的解决方案:
val tastyDish: SpicyBeans by kodein.instance(arg = M(beans, herbs))
答案 1 :(得分:1)
尝试这样的事情:
class Injector constructor(secretSauce: SecretSauce) {
val kodein = Kodein {
bind<SecretSauce> with instance(secretSauce)
bind<SpicyBeans>() with factory { beans: List<Bean>, herbs: List<Herb>
->
SpicyBeans(instance(), beans, herbs)
}
}
}
然后:
val spicyBeans by kodein.newInstance { SpicyBeans(instance(), beans, herbs) }