kosi-libs / Kodein

Painless Kotlin Dependency Injection
https://kosi-libs.org/kodein
MIT License
3.19k stars 174 forks source link

Little documentation on multi-argument factories #196

Closed benlancaster closed 5 years ago

benlancaster commented 5 years ago

Following on from stackoverflow, there is very scarce documentation on multi-argument factories.

Here's the example I used in the stackoverflow question:

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

class SecretSauce

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())
    val tastyDish: SpicyBeans = kodein.direct.instance(arg = M(beans, herbs))
  }
}

val injector = Injector(SecretSauce())
val tastyMeal = TastyMeal().initialiseWithInjector(injector.kodein)
edRibeiro commented 5 years ago

Similarly, there are also for factories with multiple arguments.

bind() from factory { id: Long, entity: String -> DetailViewModelFactory(id, entity, instance()) }

direct retrieval to fetch a dependency

private var viewModelFactory: ( (Long, String) -> DetailViewModelFactory) by factory(???) // There is something wrong here that I can not figure out how to properly recover the instance from the factory.

SalomonBrys commented 5 years ago

Documentation updated.

See #215 for multi-arg factory retrieval.

SalomonBrys commented 5 years ago

the factoryX functions are not mentioned in the doc.

romainbsl commented 5 years ago

In fact, it is https://github.com/Kodein-Framework/Kodein-DI/commit/c6948981e8a83db78a689a7ef6003af5d5554423#diff-3d89743b824a490ce02b697e73924b3bR1102

It will be available with the next release.