
이 글은 필자가 공부한 것을 정리하는 글입니다.
Hilt는 Google의 Dagger를 기반으로 만든 DI(Dependency Injection) 라이브러리 입니다.
Hilt는 Android App에 특화된 DI이며, Android class에 의존성 주입을 지원하고 생명 주기를 자동으로 관리합니다.
@HiltAndroidApp
class ExampleApplication: Application() {....}
Hilt를 사용하는 모든 앱은 HiltAndroidApp 이라는 Annotation을 Application에 포함시켜야합니다. 이 HiltAndroidApp은 Application의 기본 클래스를 비롯하여 Hilt 코드 생성을 트리거합니다.
@AndroidEntrypoint
class ExampleActivity : AppCompatActivity{....}
Hilt 삽입을 실행할 수 있는 각 안드로이드 클래스마다 InstalIn이라는 Annotaiton을 사용해주어야 하는데 구성요소 간 기간을 설정해 모듈이 어느 범위까지 사용되는지를 사용해야 합니다. 다음 표는 그 범위를 정리 해 놓은 것입니다.
| 생성된 구성요소 | 생성 위치 | 소멸 위치 |
|---|---|---|
| SingletonComponent | Application#onCreate() | Application 소멸됨 |
| ActivityRetainedComponent | Activity#onCreate() | Activity#Destroy |
| ViewModelComponent | ViewModel 생성됨 | ViewModel 소멸됨 |
| ActivityComponent | Activity#onCreate() | Activity#onDestory() |
| FragmentComponent | Fragment#onAttach() | Fragment#onDestroy() |
| ViewComponent | View#super() | View 소멸됨 |
| ViewWithFragmentComponent | View#super() | View 소멸됨 |
| ServiceComponent | Service#onCreate() | Service#onDestroy() |
다음은 Component Scopes를 나타내는 표입니다. 기본적으로 Hilt의 모든 결합은 범위가 지정되어있지 않습니다. 이 말은 앱이 결합을 요청할때 마다 Hilt는 필요한 유형의 새 instance를 생성한다는 것입니다. Hilt는 새로운 범위를 지정할 수 있는데 아래는 그 범위를 나타낸 것입니다.
| Android 클래스 | 생성된 구성요소 | 범위 |
|---|---|---|
| Application | SingletonComponent | @Singleton |
| Activity | ActivityRetainedComponent | @ActivityRetainedScoped |
| ViewModel | ViewModelComponent | @ViewModelScoped |
| Activity | ActivityComponent | @ActivityScoped |
| Fragment | FragmentComponent | @FragmentScoped |
| View | ViewComponent | @ViewScoped |
| @WithFragmentBindings 주석이 지정된 View | ViewWithFragmentComponent | @ViewScoped |
| Service | ServiceComponent | @ServiceScoped |
@Module : Hilt 모듈인지 여부를 판단
@InstallIn : Component 범위를 지정
@Binds : 인터페이스 삽입
@Provides : 인스턴스 삽입
@Qualifier : 동일한 유형에 대해 여러 결합을 제공
@ApplicationContext : Application의 context를 제공하는 한정자
이렇게 Android에서 종속성 주입에 사용되는 Hilt에 대해 알아보았습니다.