Warm tip: This article is reproduced from stackoverflow.com, please click
android kotlin dagger-2 mvp

Get Application context with Dagger2

发布于 2020-03-27 10:24:46

I make an application using the MVP pattern and I would need to have the context of the application to access the getString() method. For this, I use Dagger2 except that I don't know how to implement it

So here's what I've been doing so far:

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
    }
}

I want to provide the context of BaseApplication into the adapter of my recyclerview because I need to have access to the getString method.

What do I have to do now that I've done this to get the context in my adapter ?

Questioner
mamenejr
Viewed
66
StuStirling 2019-07-03 23:05

To provide the applicationContext in dagger, create a new scope.

@javax.inject.Qualifier
annotation class ForApplication

Then in your ApplicationModule, you provide this dependency using the scope.

@Singleton
@Provides
@NonNull
@ForApplication
fun provideContext(): Context {
    return context
}

Now anywhere you want to use this context, just prefix it with this scope. For example

@Inject
class YourAdapter extends Adapter {
    YourAdapter(@ForApplication Context context) {

    }
}