question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Dagger MissingBinding error when injecting ViewModels (dagger 2.24 with kotlin 1.3.50)

See original GitHub issue

Setup dagger v2.24 kotlin 1.3.50 Gradle 5.4.1

Error

error: [Dagger/MissingBinding] java.util.Map<java.lang.Class<? extends androidx.lifecycle.ViewModel>,javax.inject.Provider<androidx.lifecycle.ViewModel>> cannot be provided without an @Provides-annotated method.
public abstract interface AppComponent extends dagger.android.AndroidInjector<com.champion.myproject.MainApplication> {
                ^
      java.util.Map<java.lang.Class<? extends androidx.lifecycle.ViewModel>,javax.inject.Provider<androidx.lifecycle.ViewModel>> is injected at
          com.champion.myproject.di.ViewModelFactory(creators)
      com.champion.myproject.di.ViewModelFactory is injected at
          com.champion.myproject.di.module.ViewModelModule.bindViewModelFactory(factory)
      androidx.lifecycle.ViewModelProvider.Factory is injected at
          com.champion.myproject.ui.basemvvm.BaseAppCompatActivity.viewModelFactory
      com.champion.myproject.ui.main.MainActivity is injected at
          dagger.android.AndroidInjector.inject(T) [com.champion.myproject.di.AppComponent → com.champion.myproject.di.module.ActivityBindingModule_BindMainActivity.MainActivitySubcomponent]

Code

@Singleton
class ViewModelFactory @Inject constructor(
    private val creators: Map<Class<out ViewModel>,
            @JvmSuppressWildcards Provider<ViewModel>>
) : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        val creator = creators[modelClass] ?: creators.entries.firstOrNull {
            modelClass.isAssignableFrom(it.key)
        }?.value ?: throw IllegalArgumentException("unknown model class $modelClass")
        try {
            @Suppress("UNCHECKED_CAST")
            return creator.get() as T
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }
}
@Module
abstract class ViewModelModule {
    @Binds
    abstract fun bindViewModelFactory(factory : ViewModelFactory) : ViewModelProvider.Factory
}
@Module
abstract class MainModule {
    @Binds
    @IntoMap
    @ViewModelKey(MainViewModel::class)
    abstract fun bindMainViewModel(mainViewModel: MainViewModel): ViewModel
}
@MustBeDocumented
@Target(
    AnnotationTarget.FUNCTION,
    AnnotationTarget.PROPERTY_GETTER,
    AnnotationTarget.PROPERTY_SETTER
)
@Retention(AnnotationRetention.RUNTIME)
@MapKey
annotation class ViewModelKey(val value: KClass<out ViewModel>)
@Module
abstract class ActivityBindingModule {
    @ContributesAndroidInjector(modules = [MainModule::class])
    abstract fun bindMainActivity() : MainActivity
}
@Singleton
@Component(
    modules = [
        AndroidSupportInjectionModule::class,
        AppModule::class,
        ViewModelModule::class,
        ActivityBindingModule::class,
        ServiceModule::class,
        UtilModule::class
    ]
)
interface AppComponent : AndroidInjector<MainApplication> {
    @Component.Factory
    interface Factory : AndroidInjector.Factory<MainApplication>
}

if inject other class is not problem

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:7 (1 by maintainers)

github_iconTop GitHub Comments

10reactions
champChayangkooncommented, Feb 4, 2020

Remove @Singleton on top of ViewModelFactory Class move ViewModelModule into @ContributesAndroidInjector(modules = [MainModule::class,ViewModelModule ::class])

4reactions
kihakicommented, Apr 6, 2020

Remove @singleton on top of ViewModelFactory Class move ViewModelModule into @ContributesAndroidInjector(modules = [MainModule::class,ViewModelModule ::class])

Right, but then the ViewModel Factory will not be singleton scoped and will be a separate instance every time, which defeats the purpose.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Dagger MissingBinding error when injecting ViewModels
I faced same issue combining Android X and Kotlin version 1.3.0 , Dagger won't be able to create MultiBindings . To solve the...
Read more >
Issue with Dagger2 providers MissingBinding with 1.3.30
I'll try to explain as simple as possible (especially that I'm not really at ease with Dagger!). Dagger2 is used to inject class....
Read more >
Assisted Injection With Dagger and Hilt - RayWenderlich.com
How to use assisted injection with Hilt and ViewModels. Note: This tutorial assumes you're familiar with Android development and Android Studio.
Read more >
Dagger.Hilt TLDR (updated for 2.31.2-alpha) | by Lukas Vyletel
Bonus: I want to inject ViewModel into my Activity / Fragment. Provided you already have added all relevant gradle dependencies, you'll need to...
Read more >
Dagger Hilt in Android with Example - GeeksforGeeks
Note that select Kotlin as the programming language. Step 2: Adding dependencies. In order to use Dagger Hilt, we need to add the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found