Yokan / rebuild
Course 1 8624561

05-hilt-di.md

.codex/skills/compose-kotlin-agent-skills/references/05-hilt-di.md

documentation / design asset351 lines
1# Hilt Dependency Injection — Patterns, Scopes, Testing23## Contents45- Core setup6- @HiltViewModel pattern7- @Binds vs @Provides8- Scopes — when to use which9- EntryPoint for non-Hilt classes10- Hilt vs Koin — detailed comparison11- Testing with Hilt12- Anti-patterns1314## Core Setup1516```kotlin17// Application class18@HiltAndroidApp19class MyApp : Application()2021// Activity22@AndroidEntryPoint23class MainActivity : ComponentActivity()24```2526```toml27# build.gradle.kts (app)28[plugins]29hilt = { id = "com.google.dagger.hilt.android", version = "2.56.2" }30ksp = { id = "com.google.devtools.ksp", version = "2.1.20-1.0.32" }3132[dependencies]33hilt-android = { module = "com.google.dagger:hilt-android", version.ref = "hilt" }34hilt-compiler = { module = "com.google.dagger:hilt-compiler", version.ref = "hilt" }35hilt-navigation-compose = { module = "androidx.hilt:hilt-navigation-compose", version = "1.2.0" }36```3738**Use KSP, not kapt.** Kapt is deprecated and slower.3940## @HiltViewModel Pattern4142```kotlin43@HiltViewModel44class AuthViewModel @Inject constructor(45    private val repository: AuthRepository,46    private val totpGenerator: TOTPGenerator,47    private val savedStateHandle: SavedStateHandle  // free from Hilt48) : ViewModel() {4950    private val _state = MutableStateFlow(AccountsUiState())51    val state: StateFlow<AccountsUiState> = _state.asStateFlow()5253    // Navigation arg from SavedStateHandle54    private val accountId: String? = savedStateHandle["accountId"]5556    init {57        loadAccounts()58    }5960    private fun loadAccounts() {61        viewModelScope.launch {62            repository.getAllAccounts()63                .collect { accounts ->64                    _state.update { it.copy(accounts = accounts) }65                }66        }67    }68}6970// Composable usage71@Composable72fun AccountsScreen(73    viewModel: AuthViewModel = hiltViewModel()  // from hilt-navigation-compose74) {75    val state by viewModel.state.collectAsStateWithLifecycle()76    // ...77}78```7980`hiltViewModel()` scopes the ViewModel to the navigation back stack entry. Each destination gets its own instance.8182## @Binds vs @Provides8384### @Binds — Interface to Implementation Mapping8586```kotlin87@Module88@InstallIn(SingletonComponent::class)89abstract class RepositoryModule {9091    @Binds92    @Singleton93    abstract fun bindAuthRepository(94        impl: AuthRepositoryImpl95    ): AuthRepository9697    @Binds98    @Singleton99    abstract fun bindTotpGenerator(100        impl: HmacTotpGenerator101    ): TOTPGenerator102}103```104105**Use when:** you have an interface + single implementation. Generates less code than `@Provides`.106107### @Provides — Object Construction108109```kotlin110@Module111@InstallIn(SingletonComponent::class)112object DatabaseModule {113114    @Provides115    @Singleton116    fun provideDatabase(@ApplicationContext context: Context): AppDatabase {117        return Room.databaseBuilder(118            context,119            AppDatabase::class.java,120            "app_database"121        )122            .addMigrations(MIGRATION_1_2, MIGRATION_2_3)123            .build()124    }125126    @Provides127    fun provideAuthAccountDao(database: AppDatabase): AuthAccountDao {128        return database.authAccountDao()129    }130}131132@Module133@InstallIn(SingletonComponent::class)134object NetworkModule {135136    @Provides137    @Singleton138    fun provideHttpClient(): HttpClient {139        return HttpClient(OkHttp) {140            install(ContentNegotiation) { json() }141            install(Logging) { level = LogLevel.BODY }142            defaultRequest {143                url("https://api.example.com/")144                contentType(ContentType.Application.Json)145            }146        }147    }148}149```150151**Use when:** constructing third-party objects you don't own, or complex construction logic.152153### Decision Rule154155| Scenario | Use |156|----------|-----|157| Interface → Implementation | `@Binds` |158| Third-party library object | `@Provides` |159| Complex construction with params | `@Provides` |160| Builder pattern (Room, Retrofit, Ktor) | `@Provides` |161162## Scopes163164| Scope | Lives as long as | Use for |165|-------|-----------------|---------|166| `@Singleton` | Application | Database, HttpClient, shared repos |167| `@ActivityScoped` | Activity | Rarely used in Compose-first apps |168| `@ViewModelScoped` | ViewModel | State shared between composables in one screen |169| `@ActivityRetainedScoped` | Survives config change | Shared between Activity-scoped and ViewModel-scoped |170| No scope (unscoped) | New instance every injection | Stateless helpers, mappers, UseCases |171172```kotlin173// Singleton — one database for entire app174@Module175@InstallIn(SingletonComponent::class)176object DatabaseModule {177    @Provides178    @Singleton179    fun provideDatabase(/*...*/): AppDatabase = /* ... */180}181182// Unscoped — new UseCase per injection (lightweight, stateless)183class GenerateTotpCodeUseCase @Inject constructor(184    private val repo: AuthRepository185) {186    suspend operator fun invoke(accountId: String): String { /* ... */ }187}188```189190**Rule:** scope as narrow as possible. `@Singleton` only for truly shared, expensive objects.191192## EntryPoint — Non-Hilt Classes193194For classes Hilt can't inject into (Services, Workers, ContentProviders):195196```kotlin197// Define the entry point198@EntryPoint199@InstallIn(SingletonComponent::class)200interface AppBlockerServiceEntryPoint {201    fun appBlockerEngine(): AppBlockerEngine202    fun unlockSessionManager(): UnlockSessionManager203}204205// Use in AccessibilityService (Hilt can't inject here)206class RepLockAccessibilityService : AccessibilityService() {207208    private lateinit var engine: AppBlockerEngine209210    override fun onServiceConnected() {211        val entryPoint = EntryPointAccessors.fromApplication(212            applicationContext,213            AppBlockerServiceEntryPoint::class.java214        )215        engine = entryPoint.appBlockerEngine()216    }217}218```219220### WorkManager + Hilt221222```kotlin223@HiltWorker224class SyncWorker @AssistedInject constructor(225    @Assisted context: Context,226    @Assisted params: WorkerParameters,227    private val repository: AuthRepository228) : CoroutineWorker(context, params) {229230    override suspend fun doWork(): Result {231        return repository.syncAccounts()232            .fold(233                onSuccess = { Result.success() },234                onFailure = { Result.retry() }235            )236    }237}238```239240## Hilt vs Koin — Detailed Comparison241242| Aspect | Hilt | Koin |243|--------|------|------|244| **Error detection** | Compile-time (KSP) | Runtime (crash on missing dependency) |245| **KMP support** | Android only | Full (commonMain) |246| **Setup cost** | Higher (annotations, modules) | Lower (DSL) |247| **Build time impact** | KSP adds ~10-20% | Zero (no code gen) |248| **Performance** | Zero runtime reflection | Reflection at startup (small) |249| **ViewModel injection** | `hiltViewModel()` | `koinViewModel()` |250| **Testing** | `TestInstallIn`, `@UninstallModules` | `loadKoinModules()` override |251| **Navigation scoping** | Automatic with `hiltViewModel()` | Manual with `koinNavViewModel()` |252| **Community** | Google-backed, massive | JetBrains-friendly, growing |253254### Koin Setup (from Authenticator)255256```kotlin257// commonMain — shared module258val sharedModule = module {259    single { AuthRepository(get()) }260    viewModel { AuthViewModel(get()) }261}262263// androidMain — platform module264val androidModule = module {265    single<AuthAccountDao> {266        Room.databaseBuilder(get(), AppDatabase::class.java, "auth_db")267            .build()268            .authAccountDao()269    }270}271272// Initialization273fun initKoin() {274    startKoin {275        modules(sharedModule, platformModule())276    }277}278```279280**Choose Hilt when:** Android-only, want compile-time safety, team already knows Dagger.281**Choose Koin when:** KMP/CMP, want simpler setup, small-to-medium app, rapid prototyping.282283## Testing with Hilt284285### Replace Module in Tests286287```kotlin288@Module289@TestInstallIn(290    components = [SingletonComponent::class],291    replaces = [RepositoryModule::class]292)293abstract class FakeRepositoryModule {294    @Binds295    @Singleton296    abstract fun bindAuthRepository(297        impl: FakeAuthRepository298    ): AuthRepository299}300301class FakeAuthRepository : AuthRepository {302    private val accounts = MutableStateFlow<List<AuthAccount>>(emptyList())303304    override fun getAllAccounts(): Flow<List<AuthAccount>> = accounts305    override suspend fun insertAccount(account: AuthAccount) {306        accounts.update { it + account }307    }308}309```310311### ViewModel Unit Test (No Hilt Needed)312313```kotlin314class AuthViewModelTest {315    @get:Rule316    val mainDispatcherRule = MainDispatcherRule()317318    private lateinit var fakeRepo: FakeAuthRepository319    private lateinit var viewModel: AuthViewModel320321    @Before322    fun setup() {323        fakeRepo = FakeAuthRepository()324        viewModel = AuthViewModel(fakeRepo)325    }326327    @Test328    fun `adding account updates state`() = runTest {329        val account = AuthAccount("1", "Google", "test@gmail.com", "secret")330331        viewModel.onAddAccount(account)332333        viewModel.uiState.test {  // Turbine334            val state = awaitItem()335            assertEquals(1, state.accounts.size)336            assertEquals("Google", state.accounts.first().serviceName)337        }338    }339}340```341342Fakes over mocks. Mocks (Mockito/MockK) test interaction, not behavior. Fakes test the actual contract.343344## Anti-Patterns345346- **`@Singleton` on ViewModel** → wrong. Use `@HiltViewModel`. ViewModel lifecycle is managed by the framework347- **Injecting `Context` directly** → use `@ApplicationContext` or `@ActivityContext` qualifiers348- **Module per class** → one module per layer (DatabaseModule, NetworkModule, RepositoryModule). Don't create DataStoreModule + PreferencesModule + SettingsModule for 3 related bindings349- **`@Provides` when `@Binds` works** → `@Binds` generates less code. Use it for simple interface→impl mappings350- **Scoping everything as `@Singleton`** → most objects don't need to live for the app's entire lifetime. Unscoped is fine for stateless objects like mappers and UseCases351- **Injecting ViewModel into ViewModel** → never. If two ViewModels need shared state, extract to a shared `@Singleton` repository or manager352

Search chapters, reference and source filenames.