Stillie
Stillie

Reputation: 2676

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?

Upvotes: 0

Views: 532

Answers (2)

Nicholas Doglio
Nicholas Doglio

Reputation: 318

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()

Upvotes: 2

Benjamin
Benjamin

Reputation: 7368

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

}

Upvotes: 0

Related Questions