Day 23: Using Hilt for Dependency Injection in Android

🚀 Introduction

Dependency Injection (DI) is a critical design pattern in modern Android development. It helps in separating concerns, improving testability, and reducing boilerplate. Jetpack Hilt simplifies DI by offering a standard way to inject dependencies using annotations and minimal setup.


🔍 What is Hilt?

Hilt is a dependency injection library built on top of Dagger, specifically designed for Android. It integrates seamlessly with the Android app lifecycle and Jetpack components like ViewModel, WorkManager, and Navigation.


🧰 Why Use Hilt?

  • Simplifies Dagger setup
  • Reduces boilerplate
  • Provides built-in support for Android classes (Activity, Fragment, ViewModel)
  • Ensures scoped and safe object creation

⚙️ Setting Up Hilt

  1. Add dependencies in build.gradle (Project):
classpath("com.google.dagger:hilt-android-gradle-plugin:<version>")
  1. Apply plugin and dependencies in build.gradle (App):
plugins {
id 'dagger.hilt.android.plugin'
id 'kotlin-kapt'
}

dependencies {
implementation("com.google.dagger:hilt-android:<version>")
kapt("com.google.dagger:hilt-compiler:<version>")
}
  1. Add @HiltAndroidApp in your Application class:
@HiltAndroidApp
class MyApp : Application()

🧠 Understanding Annotations

AnnotationPurpose
@InjectUsed to request dependencies
@HiltAndroidAppInitializes Hilt in the Application
@AndroidEntryPointMarks entry points like Activities/Fragments
@Module & @InstallInFor providing custom dependencies
@ProvidesDefines how to create a dependency manually
@HiltViewModelFor injecting ViewModel with Hilt

📦 ViewModel Injection Example

@HiltViewModel
class MainViewModel @Inject constructor(
private val repository: MyRepository
) : ViewModel() {
// ViewModel logic here
}

In the activity:

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private val viewModel: MainViewModel by viewModels()
}

🛠️ Providing a Repository

@Module
@InstallIn(SingletonComponent::class)
object AppModule {

@Provides
fun provideRepository(api: ApiService): MyRepository {
return MyRepositoryImpl(api)
}
}

🔄 Lifecycle Integration

Hilt automatically manages the scope and lifecycle of dependencies:

  • SingletonComponent: Application scope
  • ActivityRetainedComponent: ViewModel
  • ActivityComponent, FragmentComponent, etc.

🆚 Hilt vs Dagger

HiltDagger
Easier to set upComplex boilerplate
Android-friendlyGeneral-purpose
Less flexibleHighly customizable
Faster to implementSteeper learning curve

✅ Best Practices

  • Use @Inject in constructors whenever possible
  • Avoid static singletons; use Hilt scopes
  • Keep modules focused and well-scoped
  • Use @HiltViewModel for clean ViewModel injection
  • Prefer ViewModelScoped or SingletonScoped depending on usage

🧪 Testing with Hilt

Hilt provides @HiltAndroidTest and @UninstallModules for unit and instrumentation testing.

@HiltAndroidTest
class MainViewModelTest {
@Inject lateinit var viewModel: MainViewModel
}

🧩 Key Points

  • What is Dependency Injection?
  • Why use Hilt in Android?
  • How to set up Hilt in your project
  • Hilt annotations explained: @Inject, @Module, @Provides, @HiltViewModel
  • ViewModel and Repository injection using Hilt
  • Hilt vs Dagger – Simplification
  • Best practices and common pitfalls

🧭 Continue Your Android Developer Journey

Day 10: MVVM Architecture in Android

Day 11: ViewModel in Android

Day 12: StateFlow vs LiveData

What is Hilt in Android?

Hilt is a Jetpack library built on top of Dagger that simplifies dependency injection in Android apps.

Why should I use Hilt instead of Dagger?

Hilt reduces boilerplate, integrates with Android lifecycle, and makes DI easier to implement.

How do I inject ViewModels using Hilt?

Use the @HiltViewModel annotation on your ViewModel and inject dependencies via constructor.

📌 Conclusion

Hilt reduces complexity and boilerplate in Android apps. With minimal configuration, it offers robust DI support across your app, making it scalable and testable. If you’re starting a new Android project, Hilt is a must-have tool in your architecture toolkit.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top