使用Dagger2获取应用程序上下文

时间:2019-07-03 14:43:53

标签: android kotlin dagger-2 mvp

我使用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
    }
}

我想在我的recyclerview的适配器中提供BaseApplication的上下文,因为我需要访问getString方法。

完成此操作以在适配器中获取上下文后,我现在该怎么办?

1 个答案:

答案 0 :(得分:1)

要在匕首中提供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) {

    }
}
相关问题