Why @ContributesAndroidInjector doesn't provide Android Framework type

后端 未结 2 740
梦谈多话
梦谈多话 2021-01-28 03:03

I have simplified my application to get the root of the problem and here is the simplified version. I\'m implementing Dagger 2 using following configuration:

App

2条回答
  •  萌比男神i
    2021-01-28 03:39

    You probably forgot to inject your application in MyApp. You should have something like this (you might need to modify it a bit to fit your AppComponent:

    DaggerAppComponent.builder()
        .application(this)
        .build()
        .inject(this)
    

    Also, Dagger is actually providing your MainActivity through your @ContributesAndroidInjector annotated method but that's not what you're injecting.

    You're injecting a string so Dagger is using your provideString method. Since this method requires a MainActivity instance to work, Dagger is looking for such a method annotated with @Provides. You don't have any and Dagger won't look at your @ContributesAndroidInjector method since it does not have any reasons to do so.

    If you want it to work, you actually have to define your provideString method in a separate module and install it inside your @ContributesAndroidInjector:

    @Module
    abstract class ActivityBindingModule {
        @ContributesAndroidInjector(modules = [StringModule::class])
        abstract fun mainActivity(): MainActivity
    }
    
    @Module
    class StringModule {
    
        @JvmStatic
        @Provides
        fun provideString(mainActivity: MainActivity): String = "Hehe"
    }
    

提交回复
热议问题