Hilt는 Dagger를 기반으로 한 Android 공식 의존성 주입(Dependency Injection, DI) 라이브러리입니다. Google이 제공하며, Android 앱에서 의존성 관리를 쉽게 할 수 있도록 설계되었습니다.
Gradle에 Hilt 의존성을 추가해야 합니다.
(1) build.gradle (Project)
plugins {
id 'com.android.application'
id 'kotlin-kapt'
id 'dagger.hilt.android.plugin'
}
(2) build.gradle (Module)
dependencies {
implementation "com.google.dagger:hilt-android:2.50"
kapt "com.google.dagger:hilt-android-compiler:2.50"
}
모든 앱의 최상위에서 DI를 적용하기 위해 @HiltAndroidApp을 추가합니다.
@HiltAndroidApp
class MyApplication : Application()
Hilt에서 @Module과 @InstallIn을 사용하여 의존성을 주입합니다.
@Module
@InstallIn(SingletonComponent::class) // 앱 전체에서 사용 가능
object AppModule {
@Provides
@Singleton
fun provideRetrofit(): Retrofit {
return Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}
Hilt를 사용하면 ViewModel에서도 간단하게 DI를 적용할 수 있습니다.
@HiltViewModel
class MyViewModel @Inject constructor(
private val retrofit: Retrofit
) : ViewModel() {
fun fetchData() {
// Retrofit을 사용하여 API 호출
}
}
Activity 또는 Fragment에서 @AndroidEntryPoint를 추가하면 Hilt가 자동으로 의존성을 주입합니다.
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject lateinit var retrofit: Retrofit
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Retrofit 사용 가능
}
}
Scope 설명
Hilt는 Dagger를 기반으로 하면서도 더 간편하게 의존성 주입을 사용할 수 있도록 도와줍니다. 특히, Android 컴포넌트에 특화된 DI 지원과 자동으로 Component를 설정해주는 기능 덕분에 코드가 훨씬 간결해지고 유지보수가 쉬워집니다.