Dependency Injection is essential for building maintainable, testable, and scalable Android applications.
In smaller projects, manually creating dependencies is often manageable. However, as applications grow, dependency graphs become increasingly complex.
Consider an Android application using:
- Jetpack Compose for UI
- ViewModel for presentation logic
- StateFlow for observable state
- Retrofit for network requests
- Room for local storage
- Repository Pattern for data management
- WorkManager for background tasks
Each component depends on other components.
Managing these dependencies manually can require numerous factories, containers, and initialization classes.
Hilt simplifies dependency management by generating much of the required wiring at compile time.
In this tutorial, we’ll learn how Hilt works and build a practical Notes Manager application using Kotlin, Jetpack Compose, Room, Hilt, ViewModel, StateFlow, and MVVM architecture.
We’ll also explore how to inject Retrofit, manage dependency scopes, and test Hilt-based applications.
What You’ll Learn
By the end of this tutorial, you’ll understand:
- What Hilt is and how it works
- Hilt vs Dagger
- Configuring Hilt with Gradle
- @HiltAndroidApp
- @AndroidEntryPoint
- @Inject constructor
- @HiltViewModel
- @Module and @InstallIn
- @Provides and @Binds
- Hilt components and scopes
- Repository injection
- Room database injection
- Retrofit injection
- Hilt with Jetpack Compose
- Hilt with Navigation Compose
- Hilt testing
- Common mistakes
- Production best practices
1. What Is Hilt in Android?
Hilt is a Dependency Injection library built on top of Dagger.
It provides Android-specific integration for creating, managing, and injecting dependencies.
Hilt uses annotations and generated code to connect application components.
Example Architecture
Application
|
v
Hilt Dependency Graph
|
+--------+--------+
| |
v v
Room Database Retrofit API
| |
+--------+--------+
|
v
Repository
|
v
ViewModel
|
v
Jetpack Compose UI
Why Use Hilt?
Hilt helps developers:
- Reduce manual dependency construction
- Centralize dependency configuration
- Manage shared dependency lifetimes
- Inject dependencies into ViewModels
- Replace dependencies during testing
- Detect missing bindings during compilation
Hilt is particularly useful for medium and large Android applications.
2. Hilt vs Dagger
Hilt is built on Dagger, but it provides additional Android-specific conventions.
| Feature | Dagger | Hilt |
|---|---|---|
| Dependency Injection | Yes | Yes |
| Compile-time validation | Yes | Yes |
| Android integration | Requires more manual setup | Built-in components |
| Component hierarchy | Customizable | Standardized |
| ViewModel integration | Requires setup | Built-in support |
| Dependency scopes | Supported | Android-specific scopes |
| Boilerplate | Often higher | Usually lower |
Which Should You Use?
For most new Android applications that need a DI framework, Hilt is a practical choice.
Dagger remains useful when an application requires custom dependency graphs or configurations beyond Hilt’s standard component hierarchy.
3. How Hilt Works
Hilt uses annotations to understand how dependencies should be created and supplied.
For example:
class UserRepository @Inject constructor(
private val apiService: UserApiService
)
The @Inject annotation tells Hilt that UserRepository can be constructed using its constructor.
Hilt must also know how to create UserApiService.
Once the dependency graph is complete, Hilt generates the necessary implementation code.
Important
Hilt does not automatically create every dependency.
Interfaces, third-party classes, and objects requiring custom construction often need explicit bindings.
4. Create a New Android Project
Open Android Studio and create a project.
Use the following configuration:
| Setting | Value |
|---|---|
| Project Name | HiltNotes |
| Package Name | com.example.hiltnotes |
| Language | Kotlin |
| UI Toolkit | Jetpack Compose |
| Minimum SDK | API 26 or higher |
| Architecture | MVVM |
We’ll use Kotlin DSL for Gradle configuration.
5. Configure Hilt in Gradle
Hilt requires a Gradle plugin, runtime dependency, and annotation processor.
This tutorial uses KSP (Kotlin Symbol Processing).
Root build.gradle.kts
Add the Hilt and KSP plugins to your existing plugin configuration.
plugins {
id("com.google.dagger.hilt.android") version "<hilt-version>" apply false
id("com.google.devtools.ksp") version "<ksp-version>" apply false
}
App build.gradle.kts
Apply the plugins:
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("com.google.devtools.ksp")
id("com.google.dagger.hilt.android")
}
If your project uses a version catalog, configure the same plugins through your catalog aliases instead.
Add Dependencies
dependencies {
implementation(
"com.google.dagger:hilt-android:<hilt-version>"
)
ksp(
"com.google.dagger:hilt-compiler:<hilt-version>"
)
implementation(
"androidx.hilt:hilt-navigation-compose:<androidx-hilt-version>"
)
implementation(
"androidx.lifecycle:lifecycle-viewmodel-compose:<version>"
)
implementation(
"androidx.lifecycle:lifecycle-runtime-compose:<version>"
)
implementation(
"org.jetbrains.kotlinx:kotlinx-coroutines-android:<version>"
)
}
Replace placeholders with compatible stable versions.
Important: KSP must be compatible with your Kotlin compiler version. Also follow the plugin configuration generated by your Android Studio project, particularly if it uses a newer Kotlin or Compose compiler setup.
Do not apply both KAPT and KSP to the same Hilt compiler configuration unnecessarily.
6. Understanding @HiltAndroidApp
Every Hilt-enabled Android application needs an Application class annotated with @HiltAndroidApp.
Create HiltNotesApplication.kt
package com.example.hiltnotes
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class HiltNotesApplication : Application()
Update AndroidManifest.xml
<application
android:name=".HiltNotesApplication"
... >
</application>
Keep the remaining application attributes and activities from your existing manifest.
Explanation
@HiltAndroidApp triggers Hilt’s application-level code generation.
It establishes the application component used to provide dependencies.
7. Understanding @AndroidEntryPoint
@AndroidEntryPoint enables injection into supported Android framework classes.
Example
@AndroidEntryPoint
class MainActivity : ComponentActivity()
Hilt supports integration with Android components such as Activities, Fragments, Services, and certain other framework types.
Important
Hilt ViewModels are not annotated with @AndroidEntryPoint.
They use @HiltViewModel instead.
8. Constructor Injection with @Inject
Constructor injection is the preferred way to provide dependencies for ordinary Kotlin classes.
Example
class Logger @Inject constructor() {
fun log(message: String) {
println(message)
}
}
Inject Logger into Another Class
class AnalyticsRepository @Inject constructor(
private val logger: Logger
) {
fun trackEvent(event: String) {
logger.log(event)
}
}
Explanation
Hilt understands how to construct Logger.
It can then construct AnalyticsRepository using Logger.
Benefits
- Explicit dependencies
- Less boilerplate
- Easier testing
- Compile-time dependency validation
9. Understanding @Module and @InstallIn
Not every dependency can use constructor injection.
For example, Room databases and Retrofit clients are created through builders.
Hilt modules define how these objects should be provided.
Example
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun provideAppConfig(): AppConfig {
return AppConfig()
}
}
Explanation
@Module identifies a Hilt module.
@InstallIn specifies the Hilt component that receives its bindings.
@Provides defines how to create the dependency.
@Singleton scopes the provided instance to the SingletonComponent.
10. Understanding @Provides
Use @Provides when an object requires custom construction.
Example
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@Singleton
fun provideOkHttpClient(): OkHttpClient {
return OkHttpClient.Builder()
.build()
}
}
Explanation
OkHttpClient is created using its builder.
Hilt uses the provider function when another dependency requests OkHttpClient.
11. Understanding @Binds
@Binds connects an interface to an implementation.
Repository Interface
interface UserRepository {
suspend fun getUsername(): String
}
Implementation
class UserRepositoryImpl @Inject constructor() :
UserRepository {
override suspend fun getUsername(): String {
return "Android Developer"
}
}
Binding Module
@Module
@InstallIn(SingletonComponent::class)
abstract class RepositoryModule {
@Binds
abstract fun bindUserRepository(
implementation: UserRepositoryImpl
): UserRepository
}
Explanation
When a consumer requests UserRepository, Hilt can supply UserRepositoryImpl.
@Binds vs @Provides
Use @Binds for straightforward interface-to-implementation bindings.
Use @Provides when custom object construction is required.
Practical Mini-Project: Notes Manager with Hilt, Room, and Jetpack Compose
Now we’ll build a Notes Manager application demonstrating Hilt integration across the data and presentation layers.
Features
- Create notes
- Display saved notes
- Delete notes
- Store notes locally with Room
- Observe notes using Flow
- Manage UI state with StateFlow
- Inject dependencies with Hilt
- Use MVVM architecture
Technology Stack
- Kotlin
- Jetpack Compose
- Material 3
- Hilt
- Room
- ViewModel
- StateFlow
- Coroutines
- MVVM
12. Recommended Project Structure
com.example.hiltnotes/
│
├── HiltNotesApplication.kt
├── MainActivity.kt
│
├── data/
│ ├── local/
│ │ ├── NoteEntity.kt
│ │ ├── NoteDao.kt
│ │ └── NotesDatabase.kt
│ │
│ └── repository/
│ └── NoteRepositoryImpl.kt
│
├── domain/
│ └── repository/
│ └── NoteRepository.kt
│
├── di/
│ ├── DatabaseModule.kt
│ └── RepositoryModule.kt
│
└── presentation/
├── NotesUiState.kt
├── NotesViewModel.kt
└── NotesScreen.kt
13. Add Room Dependencies
Add Room to your app module.
dependencies {
implementation(
"androidx.room:room-runtime:<room-version>"
)
implementation(
"androidx.room:room-ktx:<room-version>"
)
ksp(
"androidx.room:room-compiler:<room-version>"
)
}
Use compatible stable Room and KSP versions.
14. Step 1 — Create the Note Entity
File: data/local/NoteEntity.kt
package com.example.hiltnotes.data.local
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "notes")
data class NoteEntity(
@PrimaryKey(autoGenerate = true)
val id: Long = 0,
val title: String,
val content: String,
val createdAt: Long = System.currentTimeMillis()
)
Explanation
The entity represents a row in the Room notes table.
Each note contains:
- Unique ID
- Title
- Content
- Creation timestamp
15. Step 2 — Create the Note DAO
File: data/local/NoteDao.kt
package com.example.hiltnotes.data.local
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import kotlinx.coroutines.flow.Flow
@Dao
interface NoteDao {
@Query(
"SELECT * FROM notes ORDER BY createdAt DESC, id DESC"
)
fun observeNotes(): Flow<List<NoteEntity>>
@Insert
suspend fun insertNote(note: NoteEntity)
@Query("DELETE FROM notes WHERE id = :noteId")
suspend fun deleteNote(noteId: Long)
}
Explanation
The DAO defines database operations.
Room generates the implementation.
The observeNotes() function returns a Flow, allowing the UI to react to database changes.
16. Step 3 — Create the Room Database
File: data/local/NotesDatabase.kt
package com.example.hiltnotes.data.local
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(
entities = [NoteEntity::class],
version = 1,
exportSchema = true
)
abstract class NotesDatabase : RoomDatabase() {
abstract fun noteDao(): NoteDao
}
Explanation
NotesDatabase is the main Room database class.
It defines the entities and DAO accessors.
For production projects, configure schema export and retain schema history for future migrations.
17. Step 4 — Create the Repository Interface
File: domain/repository/NoteRepository.kt
package com.example.hiltnotes.domain.repository
import com.example.hiltnotes.data.local.NoteEntity
import kotlinx.coroutines.flow.Flow
interface NoteRepository {
fun observeNotes(): Flow<List<NoteEntity>>
suspend fun addNote(
title: String,
content: String
)
suspend fun deleteNote(noteId: Long)
}
Explanation
The repository defines the operations required by the presentation layer.
For a larger Clean Architecture project, use a domain Note model rather than exposing a Room entity through the domain contract.
18. Step 5 — Implement the Repository
File: data/repository/NoteRepositoryImpl.kt
package com.example.hiltnotes.data.repository
import com.example.hiltnotes.data.local.NoteDao
import com.example.hiltnotes.data.local.NoteEntity
import com.example.hiltnotes.domain.repository.NoteRepository
import javax.inject.Inject
import kotlinx.coroutines.flow.Flow
class NoteRepositoryImpl @Inject constructor(
private val noteDao: NoteDao
) : NoteRepository {
override fun observeNotes(): Flow<List<NoteEntity>> {
return noteDao.observeNotes()
}
override suspend fun addNote(
title: String,
content: String
) {
val trimmedTitle = title.trim()
if (trimmedTitle.isBlank()) {
return
}
noteDao.insertNote(
NoteEntity(
title = trimmedTitle,
content = content.trim()
)
)
}
override suspend fun deleteNote(noteId: Long) {
noteDao.deleteNote(noteId)
}
}
Explanation
The repository receives NoteDao through constructor injection.
It does not create the database or DAO.
Hilt will supply the DAO once its binding is configured.
19. Step 6 — Create the Hilt Database Module
File: di/DatabaseModule.kt
package com.example.hiltnotes.di
import android.content.Context
import androidx.room.Room
import com.example.hiltnotes.data.local.NoteDao
import com.example.hiltnotes.data.local.NotesDatabase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {
@Provides
@Singleton
fun provideDatabase(
@ApplicationContext context: Context
): NotesDatabase {
return Room.databaseBuilder(
context,
NotesDatabase::class.java,
"notes_database"
).build()
}
@Provides
fun provideNoteDao(
database: NotesDatabase
): NoteDao {
return database.noteDao()
}
}
Explanation
The module provides two dependencies:
- NotesDatabase
- NoteDao
Why Use @ApplicationContext?
The database requires a Context.
Application Context is appropriate for an application-scoped database.
Why Use @Singleton?
The database should normally be shared within the application process rather than repeatedly constructed.
20. Step 7 — Create the Repository Binding Module
File: di/RepositoryModule.kt
package com.example.hiltnotes.di
import com.example.hiltnotes.data.repository.NoteRepositoryImpl
import com.example.hiltnotes.domain.repository.NoteRepository
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
abstract class RepositoryModule {
@Binds
@Singleton
abstract fun bindNoteRepository(
implementation: NoteRepositoryImpl
): NoteRepository
}
Explanation
Hilt now knows that NoteRepositoryImpl satisfies requests for NoteRepository.
Because NoteRepositoryImpl uses constructor injection, Hilt can construct it using the NoteDao binding.
Complete Dependency Chain
NotesDatabase
|
v
NoteDao
|
v
NoteRepositoryImpl
|
v
NoteRepository
|
v
NotesViewModel
21. Step 8 — Create UI State
File: presentation/NotesUiState.kt
package com.example.hiltnotes.presentation
import com.example.hiltnotes.data.local.NoteEntity
data class NotesUiState(
val notes: List<NoteEntity> = emptyList(),
val isLoading: Boolean = true,
val errorMessage: String? = null
)
Explanation
The UI state describes the Notes screen.
It includes the note list, loading status, and an optional error message.
22. Step 9 — Create Hilt ViewModel
File: presentation/NotesViewModel.kt
package com.example.hiltnotes.presentation
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.hiltnotes.domain.repository.NoteRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
@HiltViewModel
class NotesViewModel @Inject constructor(
private val repository: NoteRepository
) : ViewModel() {
val uiState: StateFlow<NotesUiState> =
repository.observeNotes()
.map { notes ->
NotesUiState(
notes = notes,
isLoading = false
)
}
.catch { exception ->
if (exception is CancellationException) {
throw exception
}
emit(
NotesUiState(
isLoading = false,
errorMessage = "Unable to load notes"
)
)
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = NotesUiState()
)
fun addNote(
title: String,
content: String
) {
viewModelScope.launch {
repository.addNote(title, content)
}
}
fun deleteNote(noteId: Long) {
viewModelScope.launch {
repository.deleteNote(noteId)
}
}
}
Explanation
@HiltViewModel enables Hilt integration with Android ViewModel.
@Inject constructor tells Hilt which dependencies the ViewModel requires.
The ViewModel receives NoteRepository automatically.
Why Use StateFlow?
StateFlow exposes the current UI state to Jetpack Compose.
Why Use viewModelScope?
viewModelScope manages coroutines associated with the ViewModel lifecycle.
Production Note
This introductory example handles errors while observing notes.
For production, also handle failures from addNote() and deleteNote() and expose appropriate operation results through UI state.
23. Step 10 — Create the Jetpack Compose Notes Screen
File: presentation/NotesScreen.kt
package com.example.hiltnotes.presentation
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.example.hiltnotes.data.local.NoteEntity
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NotesScreen(
viewModel: NotesViewModel
) {
val uiState by viewModel.uiState
.collectAsStateWithLifecycle()
var title by rememberSaveable {
mutableStateOf("")
}
var content by rememberSaveable {
mutableStateOf("")
}
Scaffold(
topBar = {
TopAppBar(
title = {
Text("Hilt Notes Manager")
}
)
}
) { paddingValues ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues)
.padding(16.dp),
verticalArrangement =
Arrangement.spacedBy(12.dp)
) {
OutlinedTextField(
value = title,
onValueChange = {
title = it
},
label = {
Text("Note Title")
},
modifier = Modifier.fillMaxWidth()
)
OutlinedTextField(
value = content,
onValueChange = {
content = it
},
label = {
Text("Note Content")
},
modifier = Modifier.fillMaxWidth(),
minLines = 3
)
Button(
onClick = {
viewModel.addNote(
title = title,
content = content
)
title = ""
content = ""
},
enabled = title.isNotBlank(),
modifier = Modifier.fillMaxWidth()
) {
Text("Save Note")
}
HorizontalDivider()
Text(
text = "Saved Notes",
style = MaterialTheme.typography.titleLarge
)
when {
uiState.isLoading -> {
CircularProgressIndicator()
}
uiState.errorMessage != null -> {
Text(
text = uiState.errorMessage.orEmpty(),
color = MaterialTheme.colorScheme.error
)
}
uiState.notes.isEmpty() -> {
Text("No notes available")
}
else -> {
LazyColumn(
modifier = Modifier.weight(1f),
verticalArrangement =
Arrangement.spacedBy(8.dp)
) {
items(
items = uiState.notes,
key = { it.id }
) { note ->
NoteItem(
note = note,
onDelete = {
viewModel.deleteNote(note.id)
}
)
}
}
}
}
}
}
}
Explanation
The screen observes NotesViewModel using collectAsStateWithLifecycle().
It sends user actions to the ViewModel.
The screen does not create the repository, DAO, or database.
24. Step 11 — Create a Reusable Note Item
Add this composable to NotesScreen.kt.
@Composable
fun NoteItem(
note: NoteEntity,
onDelete: () -> Unit
) {
Card(
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement =
Arrangement.spacedBy(8.dp)
) {
Text(
text = note.title,
style = MaterialTheme.typography.titleMedium
)
Text(
text = note.content,
style = MaterialTheme.typography.bodyMedium
)
TextButton(
onClick = onDelete
) {
Text("Delete")
}
}
}
}
Explanation
NoteItem is a reusable stateless composable.
It receives note information and a callback.
This makes the component easier to preview and test.
25. Step 12 — Create MainActivity
File: MainActivity.kt
package com.example.hiltnotes
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.MaterialTheme
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.hiltnotes.presentation.NotesScreen
import com.example.hiltnotes.presentation.NotesViewModel
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(
savedInstanceState: Bundle?
) {
super.onCreate(savedInstanceState)
setContent {
MaterialTheme {
val notesViewModel: NotesViewModel =
viewModel()
NotesScreen(
viewModel = notesViewModel
)
}
}
}
}
Explanation
MainActivity is annotated with @AndroidEntryPoint.
Hilt integrates with ViewModel creation.
The NotesViewModel receives its repository without requiring a manually written ViewModel factory.
26. Expected Application UI
Initial Screen
+--------------------------------+
| Hilt Notes Manager |
| |
| Note Title |
| [ Enter title ] |
| |
| Note Content |
| [ Enter content ] |
| [ ] |
| |
| [ Save Note ] |
| |
| ------------------------------ |
| |
| Saved Notes |
| |
| No notes available |
| |
+--------------------------------+
After Saving Notes
+--------------------------------+
| Hilt Notes Manager |
| |
| [ Note Title ] |
| [ Note Content ] |
| |
| [ Save Note ] |
| |
| Saved Notes |
| |
| +----------------------------+ |
| | Learn Hilt | |
| | Dependency Injection | |
| | Delete | |
| +----------------------------+ |
| |
| +----------------------------+ |
| | Learn Room | |
| | Android Local Database | |
| | Delete | |
| +----------------------------+ |
+--------------------------------+
Explanation
When the user saves a note:
- Compose calls the ViewModel.
- The ViewModel calls NoteRepository.
- The repository inserts the note through NoteDao.
- Room updates its observable query.
- StateFlow receives the updated note list.
- Compose displays the new note.
27. How Hilt Resolves the Complete Dependency Graph
Let’s examine what happens when NotesViewModel is created.
Step 1
MainActivity requests NotesViewModel.
Step 2
Hilt examines the ViewModel constructor.
Step 3
The constructor requires NoteRepository.
Step 4
RepositoryModule binds NoteRepository to NoteRepositoryImpl.
Step 5
NoteRepositoryImpl requires NoteDao.
Step 6
DatabaseModule provides NoteDao.
Step 7
NoteDao requires NotesDatabase.
Step 8
DatabaseModule provides NotesDatabase.
Step 9
Hilt creates and connects the required dependencies.
Dependency Graph
MainActivity
|
v
NotesViewModel
|
v
NoteRepository
|
v
NoteRepositoryImpl
|
v
NoteDao
|
v
NotesDatabase
|
v
Application Context
Hilt validates the dependency graph during compilation.
Missing or conflicting bindings typically produce compile-time errors.
28. Retrofit Dependency Injection with Hilt
Hilt is commonly used to provide network dependencies.
Add Retrofit and OkHttp
dependencies {
implementation(
"com.squareup.retrofit2:retrofit:<version>"
)
implementation(
"com.squareup.retrofit2:converter-gson:<version>"
)
implementation(
"com.squareup.okhttp3:okhttp:<version>"
)
}
Create API Interface
interface UserApiService {
@GET("users")
suspend fun getUsers(): List<UserDto>
}
This assumes UserDto is defined in your data layer.
Create NetworkModule
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@Singleton
fun provideOkHttpClient(): OkHttpClient {
return OkHttpClient.Builder()
.build()
}
@Provides
@Singleton
fun provideRetrofit(
okHttpClient: OkHttpClient
): Retrofit {
return Retrofit.Builder()
.baseUrl("https://example.com/api/")
.client(okHttpClient)
.addConverterFactory(
GsonConverterFactory.create()
)
.build()
}
@Provides
fun provideUserApiService(
retrofit: Retrofit
): UserApiService {
return retrofit.create(
UserApiService::class.java
)
}
}
Explanation
Hilt provides:
- OkHttpClient
- Retrofit
- UserApiService
The repository can then receive UserApiService through constructor injection.
Important
The example URL is a placeholder.
Use your real HTTPS API endpoint in a production application.
29. Understanding Hilt Components and Scopes
Hilt provides predefined Android components.
| Hilt Component | Typical Scope |
|---|---|
| SingletonComponent | @Singleton |
| ActivityRetainedComponent | @ActivityRetainedScoped |
| ViewModelComponent | @ViewModelScoped |
| ActivityComponent | @ActivityScoped |
| FragmentComponent | @FragmentScoped |
| ServiceComponent | @ServiceScoped |
Example: Singleton Dependency
@Singleton
class AnalyticsRepository @Inject constructor()
The dependency is scoped to SingletonComponent.
Example: ViewModel-Scoped Dependency
@ViewModelScoped
class SearchSession @Inject constructor()
The dependency is shared within one Hilt ViewModel component.
Important
A scope does not mean an object is created immediately.
Hilt generally creates scoped objects when requested and reuses them within the corresponding component.
30. Understanding @ApplicationContext and @ActivityContext
Some dependencies require Android Context.
Hilt provides qualifiers to distinguish the appropriate Context.
Application Context
class PreferencesManager @Inject constructor(
@ApplicationContext private val context: Context
)
Suitable for application-level resources.
Activity Context
class DialogCoordinator @Inject constructor(
@ActivityContext private val context: Context
)
Suitable for dependencies that require the current Activity context and have an appropriate lifetime.
Best Practice
Never retain Activity Context inside a SingletonComponent-scoped dependency.
Doing so can cause memory leaks.
31. Hilt with Navigation Compose
Hilt integrates with Navigation Compose.
For a destination managed by Navigation Compose, use hiltViewModel() to obtain a Hilt ViewModel scoped to the appropriate navigation entry.
Example
@Composable
fun NotesRoute(
viewModel: NotesViewModel = hiltViewModel()
) {
NotesScreen(
viewModel = viewModel
)
}
Navigation Example
NavHost(
navController = navController,
startDestination = "notes"
) {
composable("notes") {
NotesRoute()
}
}
Explanation
hiltViewModel() retrieves a Hilt-enabled ViewModel associated with the current navigation owner.
Important
For nested navigation graphs, choose the appropriate parent back-stack entry if multiple destinations need to share the same ViewModel.
32. Testing Hilt Dependencies
Hilt supports replacing production bindings with test implementations.
Example Test Application
@HiltAndroidTest
class NotesRepositoryTest {
@get:Rule
val hiltRule = HiltAndroidRule(this)
@Before
fun setup() {
hiltRule.inject()
}
}
Explanation
@HiltAndroidTest enables Hilt testing integration.
HiltAndroidRule manages injection for the test.
Required Test Dependencies
androidTestImplementation(
"com.google.dagger:hilt-android-testing:<hilt-version>"
)
kspAndroidTest(
"com.google.dagger:hilt-compiler:<hilt-version>"
)
Configure the Hilt test runner and appropriate test environment according to the official Hilt testing documentation.
33. Replacing Dependencies in Tests
Hilt provides several mechanisms for replacing dependencies.
Examples include:
- @TestInstallIn
- @UninstallModules
- @BindValue
Example
@Module
@TestInstallIn(
components = [SingletonComponent::class],
replaces = [RepositoryModule::class]
)
abstract class FakeRepositoryModule {
@Binds
abstract fun bindRepository(
fakeRepository: FakeNoteRepository
): NoteRepository
}
Explanation
The test module replaces the production repository binding.
FakeNoteRepository must have a valid Hilt binding, such as an @Inject constructor.
Best Practice
Prefer shared test replacement modules when the same fake dependency is needed across multiple tests.
34. Common Hilt Compilation Errors
Error 1: Missing Binding
Example:
[Dagger/MissingBinding]
UserRepository cannot be provided
Cause
Hilt does not know how to construct the requested dependency.
Solution
Add an appropriate @Inject constructor, @Binds binding, or @Provides function.
Error 2: Duplicate Binding
Two bindings provide the same unqualified type.
Solution
Remove the duplicate or introduce appropriate qualifiers.
Error 3: Missing @AndroidEntryPoint
An Activity or Fragment using Hilt integration is not configured correctly.
Solution
Add @AndroidEntryPoint to the appropriate supported Android component.
Error 4: Incorrect Scope
A binding is installed in a component incompatible with its scope.
Solution
Use the scope associated with the installed component.
Error 5: KSP Compatibility Problems
The annotation processor version is incompatible with the Kotlin compiler or build setup.
Solution
Use compatible Kotlin, KSP, Android Gradle Plugin, and Hilt versions.
35. Hilt Performance Considerations
Hilt generates dependency injection code at compile time.
However, dependency construction and initialization still consume resources.
Recommendations
- Avoid unnecessary eager initialization.
- Use appropriate dependency scopes.
- Avoid heavy work inside constructors.
- Keep network clients and databases shared where appropriate.
- Do not create multiple expensive instances unnecessarily.
- Use lazy injection when it meaningfully improves startup.
- Measure startup performance using profiling tools.
Example Lazy Injection
@Inject
lateinit var analyticsProvider: dagger.Lazy<AnalyticsManager>
The dependency can be obtained when needed:
analyticsProvider.get().trackEvent("screen_open")
Use this only in supported injection contexts and when lazy creation is actually beneficial.
36. Common Hilt Mistakes
Mistake 1: Using @Provides for Every Class
Prefer constructor injection when possible.
Mistake 2: Forgetting Interface Bindings
Interfaces usually require @Binds or @Provides.
Mistake 3: Overusing @Singleton
Not every dependency should be application-scoped.
Mistake 4: Injecting Activity Context into Singletons
This can cause memory leaks.
Mistake 5: Mixing Multiple DI Strategies Without Clear Ownership
Keep dependency construction consistent.
Mistake 6: Performing Heavy Work in Constructors
Avoid unnecessary startup overhead.
Mistake 7: Creating ViewModels Manually
Use the appropriate Hilt-aware ViewModel integration.
Mistake 8: Incorrect Navigation Scoping
Ensure shared ViewModels use the intended navigation owner.
Mistake 9: Ignoring Testing
Replace external dependencies with fake implementations.
Mistake 10: Using Incompatible Build Tool Versions
Verify Kotlin, KSP, Hilt, and Android Gradle Plugin compatibility.
37. Production Best Practices
Follow these recommendations:
- Prefer constructor injection.
- Use @Binds for simple interface bindings.
- Use @Provides for custom construction.
- Choose scopes carefully.
- Keep dependencies immutable where possible.
- Avoid leaking Android Context.
- Use @HiltViewModel for Hilt-managed ViewModels.
- Keep UI components independent of data construction.
- Use repositories to abstract data access.
- Use StateFlow for observable UI state.
- Use lifecycle-aware Flow collection.
- Use Room for structured local persistence.
- Share configured Retrofit and OkHttp instances appropriately.
- Test with fake dependencies.
- Keep modules focused on related dependencies.
- Avoid unnecessary dependency graph complexity.
- Validate startup performance.
- Keep dependencies updated and compatible.
38. Hilt Quick Reference
| Annotation / Concept | Purpose |
|---|---|
| @HiltAndroidApp | Initializes Hilt application integration |
| @AndroidEntryPoint | Enables Android component injection |
| @Inject | Constructor or field injection |
| @HiltViewModel | Hilt ViewModel integration |
| @Module | Declares dependency bindings |
| @InstallIn | Specifies component installation |
| @Provides | Creates custom dependencies |
| @Binds | Binds implementation to interface |
| @Singleton | SingletonComponent scope |
| @ViewModelScoped | ViewModelComponent scope |
| @ActivityScoped | ActivityComponent scope |
| @ApplicationContext | Application Context qualifier |
| @ActivityContext | Activity Context qualifier |
| hiltViewModel() | Retrieves a Hilt ViewModel in Compose navigation |
| @HiltAndroidTest | Enables Hilt test integration |
| @TestInstallIn | Replaces bindings for tests |
39. Practical Exercises
Exercise 1: Hilt Setup
Configure Hilt in a new Android project.
Exercise 2: Constructor Injection
Create a Logger class using @Inject constructor.
Exercise 3: Interface Binding
Create a repository interface and bind its implementation using @Binds.
Exercise 4: Database Injection
Provide Room Database and DAO using @Provides.
Exercise 5: ViewModel Injection
Create a ViewModel using @HiltViewModel.
Exercise 6: Notes Manager
Build the complete Notes Manager application.
Exercise 7: Retrofit Injection
Provide Retrofit, OkHttpClient, and an API service through Hilt.
Exercise 8: Navigation Compose
Use hiltViewModel() inside a navigation destination.
Exercise 9: Hilt Testing
Replace a repository binding with a fake implementation.
Exercise 10: Scope Management
Experiment with @Singleton and @ViewModelScoped dependencies.
40. Frequently Asked Questions
What is Hilt in Android?
Hilt is a Dependency Injection library built on Dagger that provides Android-specific dependency management.
Is Hilt better than manual Dependency Injection?
Hilt reduces manual wiring for complex dependency graphs, but manual DI remains suitable for smaller applications.
What is @HiltAndroidApp?
It initializes Hilt integration at the Application level.
What is @AndroidEntryPoint?
It enables injection into supported Android framework components.
What is @HiltViewModel?
It enables Hilt-managed ViewModel creation and constructor injection.
What is the difference between @Provides and @Binds?
@Provides defines custom object creation.
@Binds connects an implementation to an abstraction.
Can Hilt inject Retrofit?
Yes.
Retrofit can be provided through a Hilt module.
Can Hilt inject Room Database?
Yes.
Room Database and DAOs can be supplied through @Provides functions.
Does Hilt support Jetpack Compose?
Yes.
Hilt integrates with ViewModels used by Jetpack Compose screens.
Does Hilt support Navigation Compose?
Yes.
Hilt ViewModels can be obtained for navigation destinations using the appropriate integration.
Is Hilt required for MVVM?
No.
MVVM can be implemented with manual DI or other dependency injection approaches.
Is Hilt suitable for production applications?
Yes.
Hilt is widely used for dependency management in Android applications.
What We’ve Learned
In this tutorial, we explored:
- Hilt Dependency Injection fundamentals
- Hilt vs Dagger
- Gradle configuration
- @HiltAndroidApp
- @AndroidEntryPoint
- Constructor injection
- @Module and @InstallIn
- @Provides and @Binds
- Hilt ViewModel integration
- Room Database injection
- Repository injection
- Practical Notes Manager application
- Retrofit injection
- Hilt scopes
- Context qualifiers
- Navigation Compose integration
- Hilt testing
- Common compilation errors
- Performance considerations
- Production best practices
Hilt simplifies dependency management in modern Android applications.
By combining Kotlin, Jetpack Compose, ViewModel, StateFlow, Room, Retrofit, and Hilt, developers can create maintainable applications with clear dependency ownership.
The key principle is simple:
Let Hilt construct and provide dependencies while application components focus on their responsibilities.
What’s Next?
In our next tutorial:
Article 45 — Advanced Hilt Dependency Injection in Android: Scopes, Qualifiers, Modules & Testing
You’ll learn:
- Advanced Hilt component hierarchy
- SingletonComponent vs ViewModelComponent
- ActivityRetainedComponent
- Custom qualifiers
- Multiple Retrofit instances
- Multiple repository implementations
- Scoped dependencies
- Lazy injection
- Provider injection
- Assisted injection concepts
- Hilt testing strategies
- Replacing dependencies
- Modularization considerations
- Dependency graph debugging
- Production best practices
Happy Coding!
Continue learning modern Android development with Moiks Developer Blog.