Home > database >  Get all instances of an interface with Dagger Hilt
Get all instances of an interface with Dagger Hilt

Time:12-15

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

CodePudding user response:

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 {
    ...
}
  • Related