Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject application context in a repository with Hilt?

I want to inject an application context into a repository class to create a room database instance inside the repository. I am using Hilt for dependency injection.

Can we use hilt for passing application context or do I have to manually pass it?

I am getting the following error:

[Dagger/MissingBinding] android.content.Context cannot be provided without an @Provides-annotated method. public abstract static class ApplicationC  implements ExartApplication_GeneratedInjector 

Context Error

like image 687
Tushar Avatar asked Jul 24 '20 11:07

Tushar


People also ask

How do you inject ViewModel in activity using hilt?

To use @HiltViewModel , you'll need to add these 2 libraries on top of the Dagger Hilt Libraries added as shared in the article above. In your ViewModel, just add @HiltViewModel before the class and the usual @Inject to the constructor. Here we auto have the savedStateHandler injected too.

What is dependency injection Hilt?

Dependency injection (DI) is a technique widely used in programming and well suited to Android development, where dependencies are provided to a class instead of creating them itself. By following DI principles, you lay the groundwork for good app architecture, greater code reusability, and ease of testing.

How do you use the hilt in Kotlin?

In order to do so, Go to app > java > package > Right-click > New > Kotlin Class/File and create a new class and name it as MainViewModel. kt. We will annotate it with @HiltViewModel which makes the models to be created using Hilt's model factory that makes it easier to be used with Activities and Fragments.


Video Answer


1 Answers

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.

like image 188
Ashu Avatar answered Sep 25 '22 13:09

Ashu