Dagger 2, Providing Application Context in Module

前端 未结 4 1223
北海茫月
北海茫月 2021-01-13 22:17

Im pretty new in Android development and newer in DI. I am using Kotlin on a personal project where I am experimenting with Dagger 2. I managed to set it up for a util class

4条回答
  •  醉梦人生
    2021-01-13 23:00

    You can try modifying your App module like this.

    @Module
    class ApplicationModule(private val application: Application) {
    
        @Provides
        @Singleton
        fun provideContext(): Context {
            return application.applicationContext
        }
    
        @Provides
        @Singleton
        fun provideSharedPreferences(context: Context): SharedPreferences {
            return context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE)
        }
    }
    

    Then you can build the dagger component like this from your Application class.

    val appComponent = DaggerAppComponent.builder()
                    .applicationModule(ApplicationModule(this))
                    .build()
    

    Inject values in presenter like this.

    application.appComponent.inject(this)
    

提交回复
热议问题