How to inject application context in a repository with Hilt?

Solution 1:

Just use @ApplicationContext annotation on your context parameter.

By annotating context with @ApplicationContext provided by Hilt, we don't need to create a provider for the application context.

import dagger.hilt.android.qualifiers.ApplicationContext

/* For hilt versions lower than v2.28.2 use ApplicationComponent instead of
SingletonComponent. ApplicationComponent is deprecated and even removed in 
some versions above v2.28.2 so better refactor it to SingletonComponent. */


@Module
@InstallIn(SingletonComponent::class)
class ProductionModule {

    @Singleton
    @Provides
    fun provideAppDatabase(@ApplicationContext appContext: Context): AppDatabase {
        return Room
            .databaseBuilder(appContext, AppDatabase::class.java, AppDatabase.DB_NAME)
            .build()
    }
}

NOTE: In case you are tempted to pass activity context as a dependency, try to use application context or rethink your use-case. Passing activity context may lead to serious implications like memory leaks. Having said that, if you know what you are doing, use @ActivityContext annotation for passing the activity context. A possible use-case might be adapters.