ContributesAndroidInjector

ContributesAndroidInjector

Dagger2出现问题,在编译时无法识别使用ContributesAndroidInjector指定的模块。

// This doesn't work
@Module
abstract class ActivityBuildersModule {

    @ContributesAndroidInjector(
            modules = [
                FragmentBuildersModule::class,
                FeatureViewModelModule::class,
            ]
    )
    abstract fun contributeMainActivity(): MainActivity
}

这是我们的模块,它导致以下错误:
javax.inject.Provider<androidx.lifecycle.ViewModel>> cannot be provided without an @Provides-annotated method.
如果我们将声明提升到类级别,则一切将按预期运行:
// This works
@Module(includes = [
    FeatureViewModelModule::class,
])
abstract class ActivityBuildersModule {

    @ContributesAndroidInjector(
            modules = [
                FragmentBuildersModule::class,
            ]
    )
    abstract fun contributeMainActivity(): MainActivity
}

请注意,此问题并非FeatureViewModelModule独有。如果将任何提供某种依赖性的模块放在@ContributesAndroidInjector内,则将无法正常工作。

仍然有趣的是,GitHub上是否有project似乎在做同样的事情而没有任何问题。我在项目之间看到的唯一区别是我们的项目在Kotlin中,而他们的项目在Java中。

一些进一步的信息:
class MyApplication : DaggerApplication(){

    override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
        return DaggerAppComponent.builder().application(this).build()
    }
}
@Singleton
@Component(
        modules = [
            AndroidInjectionModule::class,
            ActivityBuildersModule::class,
            AppModule::class]
)
interface AppComponent : AndroidInjector<MyApplication> {
    @Component.Builder
    interface Builder {
        @BindsInstance
        fun application(application: Application): Builder

        fun build(): AppComponent
    }
}
@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)
        }

    }
}
@Suppress("unused")
@Module
abstract class FeatureViewModelModule {
    @Binds
    @IntoMap
    @ViewModelKey(FeatureViewModel::class)
    abstract fun bindCompanyViewModel(featureViewModel: FeatureViewModel): ViewModel
}

有谁知道会发生什么?

最佳答案

对于@contributionAndroidInject,请删除摘要

@Module
interface ActivityBuilderModule {@ContributesAndroidInjector fun contributeAuthActivity(): MainActivity}

09-30 13:56