0

考虑以下注入器:

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使用工厂获取实例,传入List<Herb>和实例化List<Bean> 之后 TastyMeal?我在文档中找不到示例。

4

2 回答 2

3

该解决方案称为多参数工厂。关于这方面的文档非常稀缺(这是个问题,你能开一张票,以便提醒我改进文档吗?)。

同时,这是您的解决方案:

val tastyDish: SpicyBeans by kodein.instance(arg = M(beans, herbs))
于 2019-05-07T10:20:04.117 回答
2

尝试这样的事情:

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) }
于 2019-05-07T09:09:47.433 回答