Sobes.tech
Junior — Middle

How to implement dependency injection using Dagger Hilt in an Android project?

sobes.tech AI

Answer from AI

Dagger Hilt is a dependency injection library for Android that simplifies working with Dagger. To use Hilt in a project, you need to:

  1. Add dependencies in build.gradle:
// In the root build.gradle
buildscript {
    dependencies {
        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.x'
    }
}

// In the app module's build.gradle
plugins {
    id 'kotlin-kapt'
    id 'dagger.hilt.android.plugin'
}

dependencies {
    implementation 'com.google.dagger:hilt-android:2.x'
    kapt 'com.google.dagger:hilt-android-compiler:2.x'
}
  1. Annotate the Application class with @HiltAndroidApp:
@HiltAndroidApp
class MyApplication : Application() {}
  1. Inject dependencies into components (Activity, Fragment, ViewModel) using the @AndroidEntryPoint annotation:
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    @Inject lateinit var repository: MyRepository
    // ...
}
  1. Create modules with @Module and @InstallIn annotations to provide dependencies:
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
    @Provides
    fun provideRepository(): MyRepository {
        return MyRepositoryImpl()
    }
}

Thus, Hilt automatically generates components and manages the lifecycle of dependencies.

How to implement dependency injection using Dagger… - sobes.tech