2

I'm migrating DI from Koin to Dagger Hilt. I have a custom interface with many implementations, and I want to inject all the instances in a useCase as a list.

For example:

@Singleton
class MyUseCaseImpl @Inject constructor(
    private val myInterfaces: List<MyInterface>,
) : MyUseCase {
    ...
}

When I used Koin, I would do:

single<MyUseCase> {
    MyUseCaseImpl(
        myInterfaces = getKoin().getAll(),
    )
}

How can I do the same with Hilt?

I've already binded each implementation with my interface like:

@Binds
abstract fun bindFirstMyInterfaceImpl(
    firstMyInterfaceImpl: FirstMyInterfaceImpl,
): MyInterface
ZookKep
  • 481
  • 5
  • 13

1 Answers1

2

You need multibindings. Provide your dependencies with @IntoSet annotation

@Binds
@IntoSet
abstract fun bindFirstMyInterfaceImpl(
    impl: FirstMyInterfaceImpl1,
): MyInterface

@Binds
@IntoSet
abstract fun bindSecondMyInterfaceImpl(
    impl: SecondMyInterfaceImpl,
): MyInterface

But instead of List multibindings uses Set (or Map)

@Singleton
class MyUseCaseImpl @Inject constructor(
    private val myInterfaces: Set<@JvmSuppressWildcards MyInterface>,
) : MyUseCase {
    ...
}
IR42
  • 8,587
  • 2
  • 23
  • 34