How can I use Kodein's direct retrieval to fetch a dependency bound as a factory?

。_饼干妹妹 提交于 2019-12-11 14:59:35

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/56018569/how-can-i-use-kodeins-direct-retrieval-to-fetch-a-dependency-bound-as-a-factory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!