Dependency Injection with Hilt
Simplify dependency management with Hilt. Use @HiltAndroidApp, @AndroidEntryPoint, @HiltViewModel, @Module, @Provides, and @Singleton scopes.
What Is Dependency Injection?
Dependency Injection (DI) means providing an object with what it needs rather than having it create dependencies itself.
Without DI, a class creates its own dependencies — tightly coupled, hard to test. With DI, dependencies are injected from outside — loosely coupled, easy to test and swap.
Manual DI vs Hilt
Manual DI works but becomes painful at scale:
// Manual DI — you create and pass everything:
val db = AppDatabase.getInstance(context)
val dao = db.userDao()
val repo = UserRepository(dao)
val factory = UserViewModel.Factory(repo)
val viewModel = ViewModelProvider(this, factory)[UserViewModel::class.java]
// With Hilt:
// Just annotate, Hilt does the wiring
@HiltViewModel
class UserViewModel @Inject constructor(private val repo: UserRepository) : ViewModel()All lessons in this course
- ViewModel & LiveData
- Room Database
- Coroutines & Suspend Functions
- Repository Pattern
- Navigation Component
- Dependency Injection with Hilt