kosi-libs / Kodein

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

Please provide an example for allInstances usage #134

Closed andrasferenczi closed 6 years ago

andrasferenczi commented 6 years ago

First off, thank you for the great library.

I am going through a couple examples and I cannot seem to get allInstances to work.

Why does Kodein always give an empty list to the allInstances() call?

Please look at this example:

package testing

import org.kodein.di.Kodein
import org.kodein.di.erased.*
import java.util.*

interface X

class Y : X

class Z : X

fun main(args: Array<String>) {

    // Also tried with Kodein { // Without .direct
    val kodein = Kodein.direct {

        bind<X>(tag = "one") with singleton { Y() }
        bind<X>(tag = "two") with provider { Z() }
        bind<X>(tag = "three") with factory { _: Int -> object : X {} }

        bind<List<X>>(tag = "maybe") with provider { listOf(Y()) }

    }

    val instances: List<X> = kodein.allInstances<X>()

    println(Arrays.toString(instances.toTypedArray()))
}

I know binding List<X> will probably be not found due to type erasure, it is just a test.

This prints out:

[]

I expected this to return Y and Z at least, since no factory arguments are provided.

Sorry for asking this obvious question, the example in the wiki did not provide a full example.

Thank you.

andrasferenczi commented 6 years ago

I just realized calling allInstances() is the same as allInstances(tag=null) so it returns only the empty tags. Is there a way to return all tags for a specific binding?

SalomonBrys commented 6 years ago

No there's not. However, you can explore all bindings and their information by accessing kodein.container.bindings.

http://kodein.org/Kodein-DI/?5.1/core#_hack_the_container

pusolito commented 4 years ago

Is allInstances available for kodein.js?

YuryMikhailuts commented 5 months ago

Is allInstances available for kodein.js?

I join this question. It is completely unclear what is happening with allInstances in the multiplatform. What is in the picture is all that is in the official documentation for allInstances.

  1. It is not specified on which platforms it is supported.
  2. It is not explained why not on others and whether it will be.
  3. There are no allInstances replacement proposals for the multiplatform.

image