我使用MVP模式制作了一个应用程序,并且需要具有该应用程序的上下文才能访问getString()方法。为此,我使用了Dagger2,但我不知道如何实现它
所以这是我到目前为止一直在做的事情:
BaseApplication.kt
class BaseApplication: Application() {
lateinit var component: ApplicationComponent
override fun onCreate() {
super.onCreate()
instance = this
component = buildComponent()
component.inject(this)
}
fun buildComponent(): ApplicationComponent {
return DaggerApplicationComponent.builder()
.applicationModule(ApplicationModule(this))
.build()
}
fun getApplicationComponent(): ApplicationComponent {
return component
}
companion object {
lateinit var instance: BaseApplication private set
}
}
ApplicationComponent.kt
@Component(modules = arrayOf(ApplicationModule::class))
interface ApplicationComponent {
fun inject(application: Application)
}
ApplicationModule.kt
@Module
class ApplicationModule(private val context: Context) {
@Singleton
@Provides
@NonNull
fun provideContext(): Context {
return context
}
}
我想将BaseApplication的上下文提供到我的recyclerview的适配器中,因为我需要访问getString方法。
完成此操作以在适配器中获取上下文后,我现在该怎么办?
要提供applicationContext
匕首,请创建一个新的作用域。
@javax.inject.Qualifier
annotation class ForApplication
然后在您的中ApplicationModule
,使用范围提供此依赖项。
@Singleton
@Provides
@NonNull
@ForApplication
fun provideContext(): Context {
return context
}
现在,您想在任何地方使用此上下文,都在此范围之前添加前缀。例如
@Inject
class YourAdapter extends Adapter {
YourAdapter(@ForApplication Context context) {
}
}