简体   繁体   中英

Provide application context with dagger 2

Good day all,

I would like to provide application context for my AppModule class.

I would like to have a PrefsHelper be provided through out the application like I do with my ApiService class.

The code for my AppModule:

@Module
@Suppress("unused")
object AppModule {

    @Provides
    @Reusable
    @JvmStatic
    internal fun provideApiService(retrofit: Retrofit): ApiService {
        return retrofit.create(ApiService::class.java)
    }

    /**
     * Provides the Retrofit object.
     * @return the Retrofit object
     */
    @Provides
    @Reusable
    @JvmStatic
    internal fun provideRetrofitInterface(): Retrofit {
    val interceptor: HttpLoggingInterceptor = HttpLoggingInterceptor().apply {
        this.level = HttpLoggingInterceptor.Level.BODY
    }
    val client: OkHttpClient = OkHttpClient.Builder().apply { this.addInterceptor(interceptor) }.build()
    return Retrofit.Builder()
            .baseUrl(BuildConfig.BASE_URL)
            .client(client)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
            .addConverterFactory(GsonConverterFactory.create())
            .build()
}

The way I have seen it done before (In Java) is create a constructor and pass in the application context in that way. Kotlin doesnt allow that with an object

How can I have the context be provided in this class allowing me to provide PrefsHelper?

You could also use the BindsInstance annotation in your AppComponent .

So your AppComponent would look something like this:

@Singleton
@Component(modules = YOUR_MODULES)
interface AppComponent {

//Whatever injections you have

   @Component.Builder
   interface Builder {

      fun build(): AppComponent

      @BindsInstance 
      fun application(Application application): Builder      
  }
}

Then you just add the new methods to your AppComponent creation in your Application class .

DaggerAppComponent.builder().application(this).build()

Change your AppModule to something like this:

@Module
class AppModule(private val application: Application) {

    @Singleton
    @Provides
    internal fun provideApplication(): Application = application

    @Singleton
    @Provides
    internal fun providePrefs(application: Application): YourPref {
        return YourPref(application)
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM