Android Hilt ViewModel can't detect dependency

Issue

Application

@HiltAndroidApp
class MyApplication : Application()

Module

@Module
@InstallIn(ActivityComponent::class, FragmentComponent::class)
class ApplicationModule {
    @Provides
    fun provideService(): Service = ServiceImpl()
}

Fragment

@AndroidEntryPoint
class MyFragment: Fragment() {
    @Inject lateinit var service: Service
}

So far everything works, now I try to create a ViewModel and move the service inside the viewModel

ViewModel

@HiltViewModel
class WinnersViewModel @Inject constructor(
    private val service: Service
) : ViewModel()

Updated Fragment

@AndroidEntryPoint
class MyFragment: Fragment() {
    private val viewModel: WinnersViewModel by viewModels()
}

At this point I start getting compile errors

/Users/user/Desktop/Repos/App/Android/app/build/generated/source/kapt/debug/com/app/Application_HiltComponents.java:124: error: [Dagger/MissingBinding] com.comp.app.services.Service cannot be provided without an @Provides-annotated method.
  public abstract static class SingletonC implements Application_GeneratedInjector,
                         ^
      com.comp.app.services.Service is injected at
          com.comp.app.winners.WinnersViewModel(service)
      com.comp.app.winners.WinnersViewModel is injected at
          com.comp.app.winners.WinnersViewModel_HiltModules.BindsModule.binds(vm)
      @dagger.hilt.android.internal.lifecycle.HiltViewModelMap java.util.Map<java.lang.String,javax.inject.Provider<androidx.lifecycle.ViewModel>> is requested at
          dagger.hilt.android.internal.lifecycle.HiltViewModelFactory.ViewModelFactoriesEntryPoint.getHiltViewModelMap() [com.comp.app.Application_HiltComponents.SingletonC → com.comp.app.Application_HiltComponents.ActivityRetainedC → com.comp.app.Application_HiltComponents.ViewModelC]

Any idea what the problem is?

Solution

You have to choose SingletonComponent instead in your Module, Like the following:

@Module
@InstallIn(SingletonComponent::class)
class ApplicationModule {

    @Provides
    fun provideService(): Service = ServiceImpl()
}

Answered By – Younes Charfaoui

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published