How do you achieve the following using Koin DI:
single { AValidator() } bind IValidator::class
single { BValidator() } bind IValidator::class
single { CValidator() } bind IValidator::class
single { DValidator() } bind IValidator::class
In the class where I want to have all validators injected I use the following:
val validators: List<IValidator> by inject()
Expecting that all different implementations of interface IValidator are injected automatically.
I know that is actually supported in Kodein, where you would simply do:
val validators: List<IValidator> by kodein.allInstances()
Would love to know whether this is possible within Koin.
Thanks!
With Koin 2+, you can now declare your instances individually
single { AValidator() } bind IValidator::class
single { BValidator() } bind IValidator::class
single { CValidator() } bind IValidator::class
single { DValidator() } bind IValidator::class
Then use getAll<TInterface> to request all of them
val validators: List<IValidator> = getKoin().getAll()
// with lazy
val validators: List<IValidator> by lazy { getKoin().getAll<IValidator>() }
And use bind<TInterface, TImplementation> to request a single instance
val validator: IValidator = getKoin().bind<IValidator, AValidator>()
Source
https://start.insert-koin.io/#/getting-started/modules-definitions?id=additional-types
According to the documentation, I can do something like the following:
single(name = "validators") {
listOf(AValidator(), BValidator(), CValidator(), DValidator())
}
And retrieve it with:
val validators: List<IValidator> by inject(name = "validators")
It works for now, but injecting a single validator of the list above would for example not work.
For more details: https://insert-koin.io/docs/1.0/documentation/reference/index.html
Feel free to add another solution!