How can I use Kodein's direct retrieval to fet

2019-08-19 01:37发布

Consider the following injector:

class Injector constructor(secretSauce: SecretSauce) {
    val kodein = Kodein {
        bind<SpicyBeans>() with factory { beans: List<Bean>, herbs: List<Herb> ->
            SpicyBeans(secretSauce, beans, herbs)
        }
    }
}

And the following business logic:

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
  }
}

How can I use Kodein's direct injection feature to fetch a SpicyBeans instance using a factory, passing in List<Herb> and List<Bean> after TastyMeal is instantiated? I can't find an example in the documentation.

2条回答
对你真心纯属浪费
2楼-- · 2019-08-19 01:56

The solution is called multi-argument factories. The documentation about this is very scarce (This is a problem, can you open a ticket so I can be reminded to improve the doc?).

In the meantime, here is your solution:

val tastyDish: SpicyBeans by kodein.instance(arg = M(beans, herbs))
查看更多
可以哭但决不认输i
3楼-- · 2019-08-19 02:17

Try something like this:

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)
       }
    }
}

then:

val spicyBeans by kodein.newInstance { SpicyBeans(instance(), beans, herbs) }
查看更多
登录 后发表回答