SM

Dependency Injection in Android with Hilt

Sanjay MohanSanjay Mohan
AndroidDependency InjectionKotlinHiltSoftware Architecture

Dependency Injection in Android with Hilt

Date: 3/18/2025
Author: Sanjay Mohan
Tags: Android Dependency Injection Kotlin Hilt Software Architecture

Excerpt:
Dependency Injection (DI) helps decouple components and improves testability. Hilt is Android's recommended DI framework built on top of Dagger, providing a simplified way to manage dependencies.

Introduction

Dependency Injection (DI) is a design pattern used to reduce tight coupling in applications by providing objects their dependencies from external sources rather than creating them internally. In Android, this becomes essential to keep components modular and testable.

Why Hilt?

Hilt is built on top of Dagger, providing a standardized way to incorporate DI in Android apps with less boilerplate. It integrates seamlessly with Jetpack libraries like ViewModel, Navigation, WorkManager, and Room.

Key Concepts in Hilt

  • @HiltAndroidApp
    Marks the Application class and triggers Hilt’s code generation.

  • @Inject
    Tells Hilt how to provide an instance of a class.

  • @Module and @InstallIn
    Define how to create and provide dependencies.

Sample Implementation

// Application class
@HiltAndroidApp
class MyApp : Application()

// Repository
class UserRepository @Inject constructor(
    private val apiService: ApiService
)

// Module
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {

    @Provides
    fun provideApiService(): ApiService {
        return Retrofit.Builder()
            .baseUrl("https://api.example.com")
            .build()
            .create(ApiService::class.java)
    }
}

// ViewModel
@HiltViewModel
class UserViewModel @Inject constructor(
    private val repository: UserRepository
) : ViewModel() {
    // ViewModel logic
}