Setup Hilt for Android Dependency Injection

December 13, 2021

Edit Project build.gradle

buildscript {
    dependencies {
        classpath ''

Edit Module build.gradle

plugins {
    id 'kotlin-kapt'
    id ''

dependencies {
    implementation ''
    kapt ''
    implementation 'androidx.hilt:hilt-navigation-compose:1.0.0-beta01'

Create Application class

class LuaApp : Application() {


Edit AndroidManifest.xml to include the application class.

<manufest ...>


Instance Factory

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

object DataModule {
    fun provideFirestore(): FirebaseFirestore {
        return Firebase.firestore

    fun provideAuth(): FirebaseAuth {
        return Firebase.auth

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

Inject into Activity

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

Inject into ViewModel

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


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