Koin
01 / 02

Koin Fundamentals: Modules, single vs. factory

Koin: Modules, single vs. factory

Koin is a pragmatic, lightweight dependency injection framework for Kotlin. Unlike Dagger/Hilt, which generate a dependency graph at compile time via annotation processing, Koin is a pure Kotlin DSL that resolves dependencies at runtime -- simpler to set up, trading away some compile-time safety.

Starting Koin

class MyApp : Application() {
  override fun onCreate() {
    super.onCreate()
    startKoin {
      androidContext(this@MyApp)
      modules(appModule)
    }
  }
}

Defining a Module

val appModule = module {
  single { ApiClient() }
  single { UserRepository(get()) }  // get() resolves ApiClient
  factory { UserViewModelHelper(get()) }
}

single vs. factory

single { ... } registers a singleton -- the same instance is returned every time it's injected. factory { ... } creates a fresh instance on every resolution, appropriate for short-lived or request-scoped state where sharing a single instance would risk mutable-state bugs.

Injecting Dependencies

class ProfileActivity : AppCompatActivity() {
  private val userRepository: UserRepository by inject()
  // lazily resolved from the Koin container the first time it's accessed
}

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free