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:
- 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'
}
- Annotate the Application class with
@HiltAndroidApp:
@HiltAndroidApp
class MyApplication : Application() {}
- Inject dependencies into components (Activity, Fragment, ViewModel) using the
@AndroidEntryPointannotation:
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject lateinit var repository: MyRepository
// ...
}
- Create modules with
@Moduleand@InstallInannotations 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.