使用Kotlin+Dagger2.15创建依赖时遇Module未设置运行时错误求助
RetrofitApiModule must be set的错误 先来看你遇到的核心错误:
Caused by: java.lang.IllegalStateException: pk.telenorbank.easypaisa.di.modules.RetrofitApiModule must be set
这个错误的根源是你的RetrofitApiModule设计冗余,且Dagger无法自动创建它的实例,下面一步步拆解问题和解决方案:
问题分析
- 不必要的模块构造参数
你的RetrofitApiModule有一个带RetrofitMvpApi参数的构造函数:
class RetrofitApiModule(val retrofitMvpApi: RetrofitMvpApi)
Dagger默认会尝试用无参构造来创建Module实例,除非你在Component Builder中手动传入这个Module。但更关键的是——你完全不需要这个参数,因为RetrofitMvpApi本身已经用@Inject标记了构造函数,Dagger可以直接通过构造函数注入它的依赖(也就是Retrofit),自动创建实例。
- 冗余的@Provides方法
你写的provideMvpApi()方法只是返回传入的retrofitMvpApi,这完全是多余的操作。Dagger已经能通过@Inject构造函数直接提供RetrofitMvpApi的实例,不需要额外的Module来包裹。
解决方案(推荐最优解)
直接删除RetrofitApiModule,并修改你的AppComponent:
@Singleton @Component(modules = arrayOf(AppModule::class, NetworkModule::class)) interface AppComponent { fun loginComponent(loginModule: LoginModule): LoginComponent }
这样做的原因:
NetworkModule应该已经提供了Retrofit的实例(你在RetrofitApiModule中已经引入了它)RetrofitMvpApi的@Inject构造函数会让Dagger自动利用NetworkModule提供的Retrofit来创建它的实例- 去掉冗余的Module后,Dagger生成的Component Builder就不会再要求你传入
RetrofitApiModule,自然解决了报错
如果你一定要保留Module(不推荐)
如果出于某种原因必须保留RetrofitApiModule,可以修改它为无参构造,并让@Provides方法直接创建实例(但这和@Inject构造的功能重复):
@Module(includes = arrayOf(NetworkModule::class)) class RetrofitApiModule { @Provides @Singleton fun provideMvpApi(retrofit: Retrofit): RetrofitMvpApi { return RetrofitMvpApi(retrofit) } }
同时确保你在构建DaggerAppComponent时没有遗漏Module的设置(不过既然有@Inject构造,这一步完全没必要)。
最后补充一句:原代码报错的直接原因是你在EasypaisaApp.onCreate中构建DaggerAppComponent时,没有调用Builder的retrofitApiModule(...)方法传入实例,但解决冗余的Module才是根本的修复方式。
内容的提问来源于stack exchange,提问作者Zeeshan Shabbir

