Setup Hilt for Android Dependency Injection

December 13, 2021

Edit Project build.gradle

buildscript {
    dependencies {
        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.40'
    }
}

Edit Module build.gradle

plugins {
    id 'kotlin-kapt'
    id 'dagger.hilt.android.plugin'
}


dependencies {
    implementation 'com.google.dagger:hilt-android:2.40'
    kapt 'com.google.dagger:hilt-compiler:2.40'
    implementation 'androidx.hilt:hilt-navigation-compose:1.0.0-beta01'
}

Create Application class

@HiltAndroidApp
class LuaApp : Application() {

}

Edit AndroidManifest.xml to include the application class.

<manufest ...>
    <application
        android:name=".LuaApp"
        ...>

    </application>
</manufest>

Instance Factory

Use @Singleton if only single instance is shared across the application.

@Module
@InstallIn(SingletonComponent::class)
object DataModule {
    @Provides
    @Singleton
    fun provideFirestore(): FirebaseFirestore {
        return Firebase.firestore
    }

    @Provides
    @Singleton
    fun provideAuth(): FirebaseAuth {
        return Firebase.auth
    }

    @Provides
    @Singleton
    fun providePlacesClient(@ApplicationContext context: Context): PlacesClient {
        Places.initialize(context, BuildConfig.GOOGLE_PLACES_API_KEY)
        return Places.createClient(context)
    }
}

Inject into Activity

@AndroidEntryPoint
class MainActivity : ComponentActivity() {
    @Inject lateinit var auth: FirebaseAuth
}

Inject into ViewModel

@HiltViewModel
class CardViewModel @Inject constructor(
    private val db: FirebaseFirestore,
    private val auth: FirebaseAuth,
    // savedStateHandle: SavedStateHandle
    ): ViewModel() {

}

I am using Compose Navigation, thus ViewModel for screen is injected via hiltViewModel. Without hiltViewModel, you will bump into the following exception.

Caused by: java.lang.InstantiationException: java.lang.Class<.CardViewModel> has no zero argument constructor
fun CardScreen(
    viewModel: CardViewModel = viewModel()
) {
  
}
composable("card") { CardScreen(viewModel = hiltViewModel()) }

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.