Hilt - Inject a list of Interface implementations

Viewed 23

Let me show what I mean by code.

Interface:

interface MyInterface {
}

I have 2 implementation classes:

@Singleton
class Implementation1 @Inject constructor(
    private val gson: Gson,
) : MyInterface {
}
@Singleton
class Implementation2 @Inject constructor(
    @ApplicationContext private val context: Context,
) : MyInterface {
}

I need a repository class with list of implementations of MyInterface:

@Singleton
class MyRepository @Inject constructor(
    private val implementations: List<MyInterface>,
) {
}

Problem part: I am trying to inject as below:

@InstallIn(SingletonComponent::class)
@Module
object MyDiModule {
    @Provides
    fun providesImplementations(
        imp1: Implementation1,
        imp2: Implementation2,
    ): List<MyInterface> {
        return listOf(imp1, imp2)
    }
}

But I get compilation error:

/home/sayantan/AndroidStudioProjects/example/app/build/generated/hilt/component_sources/debug/com/example/ExampleApplication_HiltComponents.java:188: error: [Dagger/MissingBinding] java.util.List<? extends com.example.MyInterface> cannot be provided without an @Provides-annotated method.
  public abstract static class SingletonC implements FragmentGetContextFix.FragmentGetContextFixEntryPoint,
                         ^

Any way to achieve this?

0 Answers
Related