Back to list

Koin-style Dependency Injection

Lv.51048@mukitaro0 playsJan 2, 2026

Koin dependency injection pattern. Lightweight DI framework for Kotlin.

preview.kotlin
Kotlin
1import org.koin.core.module.dsl.*
2import org.koin.dsl.*
3import org.koin.core.component.*
4import org.koin.core.context.*
5
6interface UserRepository {
7 fun findById(id: Int): User?
8 fun save(user: User): User
9}
10
11class UserRepositoryImpl : UserRepository {
12 private val users = mutableMapOf<Int, User>()
13
14 override fun findById(id: Int) = users[id]
15 override fun save(user: User) = user.also { users[it.id] = it }
16}
17
18class UserService(private val repository: UserRepository) {
19 fun getUser(id: Int) = repository.findById(id)
20 fun createUser(name: String, email: String): User {
21 val user = User(users.size + 1, name, email)
22 return repository.save(user)
23 }
24}
25
26val appModule = module {
27 singleOf(::UserRepositoryImpl) { bind<UserRepository>() }
28 singleOf(::UserService)
29}
30
31class MyApplication : KoinComponent {
32 private val userService: UserService by inject()
33
34 fun run() {
35 val user = userService.createUser("Alice", "alice@example.com")
36 println("Created: ${user.name}")
37 }
38}

Custom problems are not included in rankings