Hilt cannot bind interface when using AssistedInject

491 views Asked by At

Our app follows clean architecture so in the domain layer we have an Interface and a use-case like this:

interface MyRepository {
    suspend fun doSomething(): Result<String>
}

class MyUseCase @Inject constructor(private val repository: MyRepository) {
    // implementation
}

In the data layer, we have an implementation of the MyRepository for example called MyRepositoryImpl. And we bind the repository like this:

@Binds
abstract fun binMyRepostory(repository: MyRepositoryImpl): MyRepository

And we use @AssistedInject in our view model like this:

class MyViewModel @AssistedInject constructor(
    private val myUseCase: MyUseCase,
    @Assisted private var id: Int
) : ViewModel() { 

    @AssistedFactory
    interface Factory {
        fun create(id: Int): MyViewModel
    }

    companion object {
        fun provideFactory(
            assistedFactory: Factory,
            id: Int
        ): ViewModelProvider.Factory = object : ViewModelProvider.Factory {
            override fun <T : ViewModel> create(modelClass: Class<T>): T {
                return assistedFactory.create(id) as T
            }
        }
    }

}

Running the app shows this error but in a view model without AssistedInject it works properly.

It error: [Dagger/MissingBinding] package.MyRepository cannot be provided without an @Provides-annotated method.
1

There are 1 answers

0
Augusto Carmo On

Check where the module that creates that dependecy is installed in.

I've also just had that problem and noticed that I was installing my module in ViewModelComponent::class.

Probably due to the removal of @HiltViewModel from the ViewModel class, the installation in the ViewModelComponent::class makes that problem occur.

To solve the problem I had to change the component where my module is installed in to, for example, SingletonComponent::class.