0

I'm building a Kotlin CLI application using Koin. I have multiple Feature classes (each representing a functionality), and I register them as follows:

// FeatureModule.kt
val FeatureModule = module {
    factory<Feature> { QuickHealthyMealsFeature(get()) }  // number = 1
    factory<Feature> { IraqiMealsFeature(get()) }         // number = 2
    factory<Feature> { GuessGameFeature(get()) }          // number = 5
    factory<Feature> { SeafoodMealsFeature(get()) }       // number = 14

    factory<Map<Int, Feature>> {
        getAll<Feature>().associateBy { it.number }
    }

    single { FoodChangeMoodConsoleUI(get()) }
}

Each Feature class implements this interface:
interface Feature {
    val number: Int
    val name: String
    fun execute()
}

In FoodChangeMoodConsoleUI, I receive the injected map and show options like this:

class FoodChangeMoodConsoleUI(private val features: Map<Int, Feature>) {
    fun start() {
        println("=== Please enter one of the following numbers ===")
        features.forEach { (k, v) -> println("$k. ${v.name}") }
    }
}

The problem is : Only one feature (e.g., SeafoodMealsFeature) gets injected. The console prints: 14. Show seafood meals sorted by protein

What I tried:

-Checked that all Feature classes override number uniquely. -Made sure FeatureModule is passed to startKoin. -Verified that the use cases each feature needs are also registered.

Why does getAll() only return one implementation? How can I get Koin to inject all feature classes correctly into the Map<Int, Feature>?

1
  • The issue was Koin only keeping one Feature implementation when using ``` factory<Feature> { ... }. ``` The fix was to change it to: ``` factory { QuickHealthyMealsFeature(get()) } bind Feature::class ``` This way, Koin retains all bindings and getAll<Feature>() works correctly. Commented Apr 17 at 12:47

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.