kotlin-di
Dependency Injection - Hilt, Koin, scopes, testing
When & Why to Use This Skill
This Claude skill provides expert guidance and code implementation for Kotlin Dependency Injection (DI) using Hilt and Koin frameworks. It helps developers build modular, maintainable, and testable applications by automating the setup of dependency graphs, managing component scopes, and providing troubleshooting solutions for common DI-related issues in Android and Multiplatform environments.
Use Cases
- Architecting Android applications with Hilt to automate dependency provisioning for ViewModels, Activities, and Fragments.
- Configuring Koin for Kotlin Multiplatform (KMP) projects to achieve lightweight and flexible dependency injection across different platforms.
- Creating robust testing environments by utilizing Hilt's testing APIs and mocking dependencies for unit and integration tests.
- Resolving complex DI errors such as missing bindings, scope mismatches, or injection failures in Jetpack Compose.
| name | kotlin-di |
|---|---|
| description | Dependency Injection - Hilt, Koin, scopes, testing |
| version | "1.0.0" |
| sasmp_version | "1.3.0" |
| bonded_agent | 02-kotlin-android |
| bond_type | SECONDARY_BOND |
| timeout_ms | 30000 |
| max_attempts | 3 |
| backoff | exponential |
| initial_delay_ms | 1000 |
| - name | platform |
| type | string |
| validation | "^(hilt|koin)$" |
| default | "android" |
| level | info |
| events | [skill_invoked, framework_loaded, error_occurred] |
Kotlin DI Skill
Dependency Injection with Hilt and Koin.
Topics Covered
Hilt for Android
@HiltAndroidApp
class App : Application()
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides @Singleton
fun provideDatabase(@ApplicationContext context: Context) =
Room.databaseBuilder(context, AppDatabase::class.java, "app.db").build()
@Provides
fun provideUserDao(db: AppDatabase) = db.userDao()
}
@HiltViewModel
class UserViewModel @Inject constructor(
private val repository: UserRepository
) : ViewModel()
Koin for Multiplatform
val appModule = module {
single { HttpClient(getEngine()) }
single { UserRepository(get()) }
viewModel { UserViewModel(get()) }
}
// Start Koin
startKoin {
modules(appModule)
}
// Inject
val repository: UserRepository by inject()
Testing with DI
@HiltAndroidTest
class UserViewModelTest {
@get:Rule val hiltRule = HiltAndroidRule(this)
@BindValue @JvmField
val repository: UserRepository = mockk()
@Inject lateinit var viewModel: UserViewModel
@Before fun setup() { hiltRule.inject() }
}
Troubleshooting
| Issue | Resolution |
|---|---|
| "No binding for..." | Add @Provides or @Binds |
| ViewModel not injected | Use hiltViewModel() in Compose |
Usage
Skill("kotlin-di")