Dagger报错:重复包含带作用域绑定的模块,求解决方案
解决Dagger错误:repeats modules with scoped bindings or declarations
错误原因
问题出在父组件AppComponent非法引用了子组件的带作用域模块:
- AppComponent标记了
@Singleton作用域,但你把CurrentWeatherModule、WeatherForecastModule、AstronomyModule这三个带子组件专属作用域的模块加到了AppComponent的modules列表里。Dagger不允许父组件包含带有子组件作用域的绑定模块——作用域是组件专属的,父组件无法提供子组件作用域的实例,直接导致重复绑定冲突。 - 同时你在App类构建
DaggerAppComponent时还手动传入了这三个子模块,属于多余操作,进一步加剧了冲突。
修复步骤
1. 修正AppComponent,移除子组件模块
把AppComponent中modules列表里的CurrentWeatherModule::class、WeatherForecastModule::class、AstronomyModule::class删掉,只保留父组件自身的模块:
package com.ghostdev.skycast.presentation.di import dagger.Component import javax.inject.Singleton @Singleton @Component(modules = [AppModule::class, WeatherDataModule::class]) interface AppComponent { fun currentWeatherComponent(): CurrentWeatherSubComponent.Factory fun weatherForecastComponent(): WeatherForecastSubComponent.Factory fun astronomyComponent(): AstronomySubComponent.Factory }
2. 修正App类的组件构建代码
去掉构建DaggerAppComponent时传入的三个子模块,因为父组件不再依赖它们:
override fun onCreate() { super.onCreate() appComponent = DaggerAppComponent.builder() .weatherDataModule(WeatherDataModule(BuildConfig.API_KEY, location)) .build() }
3. 确认子组件与模块的绑定关系
保持子组件和对应模块的绑定不变,每个子组件只引用自己的专属模块,确保作用域匹配正确:
比如AstronomySubComponent的定义无需修改:
@AstronomyScope @Subcomponent(modules = [AstronomyModule::class]) interface AstronomySubComponent { // 原有代码 }
核心逻辑说明
Dagger的作用域规则是:每个带作用域的绑定只能属于一个组件。父组件(Singleton)的作用域层级高于子组件,不能包含子组件的作用域绑定。子组件的模块应该完全由子组件自己管理,父组件只需要提供子组件的工厂即可,不需要介入子组件的模块绑定。
内容的提问来源于stack exchange,提问作者AdrianIK
相关产品推荐
相关产品推荐

