我正在学习Dagger 2以构建一个干净的建筑项目。我一直在寻找关于同一错误的一些SO问题,但仍无法弄清为什么它不起作用。
我已经运行了调试器,以查看我的View Activity是否将发送给演示者,但似乎没有注入演示者,因为它没有提供给演示者。
这是我向“演示者”注入的活动。
@Inject lateinit var presenter : ApodDetailPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_apod_detail)
(application as SimpleMVPApplication).apodComponent.inject(this)
fetchApodDetails()
imageview_apoddetail_reloadDetail.bringToFront()
}
@Module
class PresenterModule {
@Provides
@Singleton
fun provideApodDetailPresenter(): ApodDetailPresenter {
return ApodDetailPresenter(ApodDetailsInteractorImpl(), ImageCacheImpl())
}
}
@Singleton
@Component(modules = [AppModule::class, PresenterModule::class])
interface AppComponent {
fun inject(target: ApodDetail)
}
@Module
class AppModule(private val app: Application) {
@Provides
@Singleton
fun provideContext(): Context = app
}
class SimpleMVPApplication: Application() {
lateinit var apodComponent: AppComponent
override fun onCreate() {
super.onCreate()
apodComponent = initDagger(this)
}
private fun initDagger(app: SimpleMVPApplication): AppComponent =
DaggerAppComponent.builder()
.appModule(AppModule(app))
.build()
}
这是我要插入ApodDetail.kt
class ApodDetailPresenter @Inject constructor(apodInteractor: ApodDetailsInteractorImpl, cache: ImageCacheImpl): ApodDetailContract.Presenter {
var view: ApodDetailContract.View? = null
var apodInteractor: ApodDetailsInteractorImpl? = null
var cache: ImageCacheImpl? = null
init {
this.view = view
this.apodInteractor = apodInteractor
this.cache = cache
}
就像我上面说的那样,这并不是将演示者注入到我的活动中。
答案 0 :(得分:0)
在您的Application类中,您缺少在组件构建器中添加presenter模块的调用。您需要:
private fun initDagger(app: SimpleMVPApplication): AppComponent =
DaggerAppComponent.builder()
.appModule(AppModule(app))
.presenterModule(PresenterModule())
.build()