Dependency injection

suggest change

Dependency injection (DI) means that an object gets the things it needs (its dependencies) from the outside instead of creating them itself. A SignupService that needs a database and a mailer takes them as constructor parameters, and somebody else decides which database and which mailer to pass.

That's the whole idea. You don't need a framework for it. Kotlin's constructors, default arguments, function types and lazy cover most programs. Libraries like Koin, Dagger/Hilt and kotlin-inject automate the wiring when an application grows.

This article covers:

The problem: hard-coded dependencies

Here's a class that creates its own dependencies:

import java.time.Instant

class SmtpMailer {
    fun send(to: String, body: String) = println("SMTP -> $to: $body")
}

class UserRepository {
    private val users = mutableMapOf<String, String>()
    fun save(email: String, name: String) { users[email] = name }
}

class SignupService {
    private val repo = UserRepository()      // hard-coded
    private val mailer = SmtpMailer()        // hard-coded

    fun signUp(email: String, name: String) {
        repo.save(email, name)
        mailer.send(email, "Welcome, $name! (${Instant.now()})")
    }
}

fun main() {
    SignupService().signUp("ann@example.com", "Ann")
}
SMTP -> ann@example.com: Welcome, Ann! (2026-10-17T19:26:19.125438700Z)

It works, but:

Constructor injection

Move the dependencies into the constructor and type them as interfaces:

import java.time.Clock
import java.time.Instant
import java.time.ZoneOffset

interface Mailer {
    fun send(to: String, body: String)
}

interface UserRepository {
    fun save(email: String, name: String)
    fun exists(email: String): Boolean
}

class ConsoleMailer : Mailer {
    override fun send(to: String, body: String) = println("mail -> $to: $body")
}

class InMemoryUserRepository : UserRepository {
    private val users = mutableMapOf<String, String>()
    override fun save(email: String, name: String) { users[email] = name }
    override fun exists(email: String) = email in users
}

class SignupService(
    private val repo: UserRepository,
    private val mailer: Mailer,
    private val clock: Clock,
) {
    fun signUp(email: String, name: String): Boolean {
        if (repo.exists(email)) return false
        repo.save(email, name)
        mailer.send(email, "Welcome, $name! Joined at ${Instant.now(clock)}")
        return true
    }
}

fun main() {
    val clock = Clock.fixed(Instant.parse("2026-01-15T10:00:00Z"), ZoneOffset.UTC)
    val service = SignupService(InMemoryUserRepository(), ConsoleMailer(), clock)
    println(service.signUp("ann@example.com", "Ann"))
    println(service.signUp("ann@example.com", "Ann"))
}
mail -> ann@example.com: Welcome, Ann! Joined at 2026-01-15T10:00:00Z
true
false

Kotlin makes this cheap: a primary constructor with private val parameters declares the dependency, stores it and makes it a read-only field in one line. The dependencies are val, so they can't change after construction, and they're non-null, so the object can't exist without them.

java.time.Clock is a dependency too. "Current time" is hidden global state, and injecting a Clock (Clock.systemUTC() in production, Clock.fixed(...) in tests) makes time-dependent code deterministic.

Testing with fakes

Because SignupService only knows the interfaces, a test can pass in hand-written fakes:

class RecordingMailer : Mailer {
    val sent = mutableListOf<Pair<String, String>>()
    override fun send(to: String, body: String) { sent += to to body }
}

fun main() {
    val mailer = RecordingMailer()
    val clock = Clock.fixed(Instant.parse("2026-01-15T10:00:00Z"), ZoneOffset.UTC)
    val service = SignupService(InMemoryUserRepository(), mailer, clock)

    check(service.signUp("bob@example.com", "Bob"))
    check(!service.signUp("bob@example.com", "Bob"))

    check(mailer.sent.size == 1)
    println(mailer.sent.single())
}
(bob@example.com, Welcome, Bob! Joined at 2026-01-15T10:00:00Z)

No mocking library, no network, no flaky timestamps. If you'd rather generate test doubles, MockK works the same way with injected dependencies; see Mocks and test doubles. Without injection, neither approach is possible.

Functions as dependencies

When a dependency has a single operation, you don't need an interface. A function type works, and default arguments give production values so callers don't have to pass anything:

import java.time.Instant
import java.util.UUID

class OrderService(
    private val now: () -> Instant = Instant::now,
    private val newId: () -> String = { UUID.randomUUID().toString() },
    private val log: (String) -> Unit = ::println,
) {
    fun place(item: String): String {
        val id = newId()
        log("order $id for $item at ${now()}")
        return id
    }
}

fun main() {
    // production: defaults
    OrderService().place("book")

    // test: deterministic values, captured log
    val lines = mutableListOf<String>()
    var next = 0
    val service = OrderService(
        now = { Instant.parse("2026-03-01T12:00:00Z") },
        newId = { "id-${++next}" },
        log = { lines += it },
    )
    service.place("pen")
    service.place("ink")
    println(lines)
}
order ef849a68-dbdd-445f-97ac-ad5157bd698a for book at 2026-10-17T19:26:50.702350300Z
[order id-1 for pen at 2026-03-01T12:00:00Z, order id-2 for ink at 2026-03-01T12:00:00Z]

Named arguments make it clear which dependency each lambda replaces (see Named and optional parameters). For larger function types, a type alias such as typealias IdGenerator = () -> String keeps signatures readable.

Default arguments for dependencies are fine for small things like clocks, ID generators and loggers. Don't use them for heavy dependencies such as a database connection: a default Database() quietly opens a real connection in every test that forgets to pass one.

The composition root: wiring by hand

Somebody has to create the real objects and connect them. Do it in one place, near main, called the composition root. The rest of the code just declares what it needs and never creates its own services.

A container class with by lazy properties is all you need:

data class Config(val dbUrl: String, val smtpHost: String)

class Database(url: String) {
    init { println("open database $url") }
    fun query(sql: String) = "result of '$sql'"
}

interface Mailer { fun send(to: String, body: String) }

class SmtpMailer(host: String) : Mailer {
    init { println("connect to SMTP $host") }
    override fun send(to: String, body: String) = println("mail -> $to: $body")
}

class UserRepository(private val db: Database) {
    fun find(id: Int) = db.query("select * from users where id = $id")
}

class ReportService(private val users: UserRepository, private val mailer: Mailer) {
    fun sendReport(userId: Int, to: String) = mailer.send(to, users.find(userId))
}

class RequestHandler(private val users: UserRepository, val requestId: Int) {
    fun handle(userId: Int) = "[$requestId] ${users.find(userId)}"
}

// All wiring lives in one place: the composition root.
class AppContainer(config: Config) {
    val database by lazy { Database(config.dbUrl) }
    val mailer: Mailer by lazy { SmtpMailer(config.smtpHost) }
    val userRepository by lazy { UserRepository(database) }
    val reportService by lazy { ReportService(userRepository, mailer) }

    // a new instance on every call
    private var requests = 0
    fun requestHandler() = RequestHandler(userRepository, ++requests)
}

fun main() {
    val app = AppContainer(Config("jdbc:sqlite:app.db", "smtp.example.com"))
    println("container created")

    println(app.requestHandler().handle(1))
    println(app.requestHandler().handle(2))
    app.reportService.sendReport(1, "boss@example.com")
    println(app.userRepository === app.userRepository)
}
container created
open database jdbc:sqlite:app.db
[1] result of 'select * from users where id = 1'
[2] result of 'select * from users where id = 2'
connect to SMTP smtp.example.com
mail -> boss@example.com: result of 'select * from users where id = 1'
true

Things to notice:

This manual approach scales further than people expect. Android's official guidance starts with exactly this pattern ("manual dependency injection") before introducing Hilt.

Overriding dependencies in tests

Make the container open and override the parts that touch the outside world:

interface Mailer { fun send(to: String, body: String) }

class SmtpMailer : Mailer {
    init { println("connecting to SMTP...") }
    override fun send(to: String, body: String) = println("SMTP -> $to")
}

class RecordingMailer : Mailer {
    val sent = mutableListOf<String>()
    override fun send(to: String, body: String) { sent += to }
}

class Notifier(private val mailer: Mailer) {
    fun welcome(user: String) = mailer.send(user, "Welcome!")
}

open class AppContainer {
    open val mailer: Mailer by lazy { SmtpMailer() }
    val notifier by lazy { Notifier(mailer) }
}

class TestContainer : AppContainer() {
    override val mailer = RecordingMailer()
}

fun main() {
    val app = TestContainer()
    app.notifier.welcome("ann@example.com")
    println(app.mailer.sent)
}
[ann@example.com]

SmtpMailer is never created ("connecting to SMTP..." isn't printed), and everything else is still wired the real way. Because the base container uses lazy, mailer is read after TestContainer finished initializing. If the base class read an open property in its constructor or init block, it would see the subclass field before it was set (null).

Don't use global singletons as dependencies

A Kotlin object is a convenient singleton, and it's tempting to call it directly:

object Db {
    fun query(sql: String): String = TODO()
}

class UserRepository {
    fun find(id: Int) = Db.query("...") // hidden dependency
}

This is a hard-coded dependency again: tests can't replace Db, and state leaks between tests. Using object for implementations is fine; just pass the object in through the constructor (UserRepository(db: Database)) so callers can choose a different one.

The same goes for the service locator pattern, where classes pull dependencies from a global registry (ServiceLocator.get<Mailer>()). It's better than new-ing everything, but the dependencies are again invisible in the constructor and a missing registration fails at runtime.

How a DI container works

DI libraries keep a map from a type to a recipe that creates it. Here's a minimal container with singletons, factories and cycle detection, built with KClass and reified generics:

import kotlin.reflect.KClass

class Container {
    private class Binding(val singleton: Boolean, val create: Container.() -> Any)

    private val bindings = mutableMapOf<KClass<*>, Binding>()
    private val singletons = mutableMapOf<KClass<*>, Any>()
    private val resolving = ArrayDeque<KClass<*>>()

    fun <T : Any> single(type: KClass<T>, create: Container.() -> T) {
        bindings[type] = Binding(true, create)
    }

    fun <T : Any> factory(type: KClass<T>, create: Container.() -> T) {
        bindings[type] = Binding(false, create)
    }

    inline fun <reified T : Any> single(noinline create: Container.() -> T) = single(T::class, create)
    inline fun <reified T : Any> factory(noinline create: Container.() -> T) = factory(T::class, create)

    @Suppress("UNCHECKED_CAST")
    fun <T : Any> get(type: KClass<T>): T {
        singletons[type]?.let { return it as T }
        val binding = bindings[type] ?: error("no binding for ${type.simpleName}")
        check(type !in resolving) {
            "dependency cycle: ${(resolving + type).joinToString(" -> ") { it.simpleName!! }}"
        }
        resolving.addLast(type)
        try {
            val instance = binding.create(this) as T
            if (binding.singleton) singletons[type] = instance
            return instance
        } finally {
            resolving.removeLast()
        }
    }

    inline fun <reified T : Any> get(): T = get(T::class)
}

interface Greeter { fun greet(name: String): String }
class EnglishGreeter : Greeter { override fun greet(name: String) = "Hello, $name" }
class Counter { var n = 0 }
class App(val greeter: Greeter, val counter: Counter)

class A(val b: B)
class B(val a: A)

fun main() {
    val c = Container().apply {
        single<Greeter> { EnglishGreeter() }
        factory { Counter() }
        factory { App(get(), get()) }
    }

    val app1 = c.get<App>()
    val app2 = c.get<App>()
    println(app1.greeter.greet("Kotlin"))
    println("same greeter: ${app1.greeter === app2.greeter}")
    println("same counter: ${app1.counter === app2.counter}")

    c.single { A(get()) }
    c.single { B(get()) }
    try {
        c.get<A>()
    } catch (e: IllegalStateException) {
        println(e.message)
    }
    try {
        c.get<String>()
    } catch (e: IllegalStateException) {
        println(e.message)
    }
}
Hello, Kotlin
same greeter: true
same counter: false
dependency cycle: A -> B -> A
no binding for String

App(get(), get()) works because the compiler infers the type argument of each get() from the constructor parameter it's passed to. Koin's DSL is built on the same trick.

This container isn't thread-safe and doesn't support generic types (List<String> and List<Int> share one KClass), which is where a real library earns its keep. Notice also the downside of every runtime container: "no binding for String" is something the compiler could have told you with the hand-written AppContainer.

Koin

Koin is a lightweight DI library written in Kotlin. It has no code generation and no reflection: you describe the wiring in a Kotlin DSL and Koin resolves it at runtime. It supports Kotlin Multiplatform, Android, Ktor and Compose.

Add it to build.gradle.kts:

dependencies {
    implementation("io.insert-koin:koin-core:4.2.2")
}

Define modules, start Koin and ask for instances:

import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import org.koin.core.context.startKoin
import org.koin.core.context.stopKoin
import org.koin.core.module.dsl.factoryOf
import org.koin.core.module.dsl.singleOf
import org.koin.core.parameter.parametersOf
import org.koin.core.qualifier.named
import org.koin.dsl.bind
import org.koin.dsl.module

data class Config(val dbUrl: String)

class Database(config: Config) {
    init { println("open ${config.dbUrl}") }
    fun query(sql: String) = "rows for '$sql'"
}

interface UserRepository { fun find(id: Int): String }

class SqlUserRepository(private val db: Database) : UserRepository {
    override fun find(id: Int) = db.query("select * from users where id = $id")
}

class UserService(private val repo: UserRepository) {
    fun describe(id: Int) = "user $id: ${repo.find(id)}"
}

class RequestContext(val requestId: String)

class Cli : KoinComponent {
    private val users: UserService by inject()
    private val banner: String by inject(named("banner"))

    fun run() {
        println(banner)
        println(users.describe(42))
    }
}

val appModule = module {
    single { Config(dbUrl = "jdbc:sqlite:app.db") }
    singleOf(::Database)
    singleOf(::SqlUserRepository) bind UserRepository::class
    factoryOf(::UserService)
    factory { params -> RequestContext(params.get()) }
    single(named("banner")) { "== my app ==" }
}

fun main() {
    val koin = startKoin { modules(appModule) }.koin

    Cli().run()

    val s1 = koin.get<UserService>()
    val s2 = koin.get<UserService>()
    println("factory gives new instances: ${s1 !== s2}")
    println("single is shared: ${koin.get<Database>() === koin.get<Database>()}")

    val ctx = koin.get<RequestContext> { parametersOf("req-7") }
    println(ctx.requestId)

    stopKoin()
}
== my app ==
open jdbc:sqlite:app.db
user 42: rows for 'select * from users where id = 42'
factory gives new instances: true
single is shared: true
req-7

The main parts of the DSL:

Definition Meaning
single { ... } one shared instance, created on first use
factory { ... } a new instance on every get()
singleOf(::Foo) / factoryOf(::Foo) same, but Koin calls the constructor and fills every parameter with get()
bind Interface::class also register the instance under an interface type
named("x") a qualifier to tell apart several definitions of the same type
params.get() + parametersOf(...) values supplied by the caller at get() time
by inject() lazy property that resolves from the global Koin instance

by inject() in KoinComponent is a service locator: Cli reaches into global state instead of declaring its dependencies. Use it only at the edges, where you don't control construction (Android activities, main, framework entry points). Everywhere else, write normal constructors and let singleOf/factoryOf call them. Then the classes don't know Koin exists, and you can still create them by hand in tests.

Testing with Koin

koinApplication { } creates an isolated Koin instance without touching global state, which is what you want in tests. A test module can replace production definitions:

import org.koin.core.module.dsl.factoryOf
import org.koin.core.module.dsl.singleOf
import org.koin.dsl.bind
import org.koin.dsl.koinApplication
import org.koin.dsl.module

interface Mailer { fun send(to: String, body: String) }

class SmtpMailer : Mailer {
    override fun send(to: String, body: String) = println("SMTP -> $to")
}

class RecordingMailer : Mailer {
    val sent = mutableListOf<String>()
    override fun send(to: String, body: String) { sent += to }
}

class Notifier(private val mailer: Mailer) {
    fun notify(user: String) = mailer.send(user, "hi")
}

class Billing(private val gateway: PaymentGateway)
interface PaymentGateway

val appModule = module {
    singleOf(::SmtpMailer) bind Mailer::class
    factoryOf(::Notifier)
}

val testModule = module {
    single<Mailer> { RecordingMailer() }
}

fun main() {
    // isolated instance: no global state, safe in tests
    val koin = koinApplication {
        allowOverride(true)
        modules(appModule, testModule) // later modules override earlier ones
    }.koin

    koin.get<Notifier>().notify("ann@example.com")
    println((koin.get<Mailer>() as RecordingMailer).sent)

    val broken = koinApplication { modules(module { factoryOf(::Billing) }) }.koin
    try {
        broken.get<Billing>()
    } catch (e: Exception) {
        println(e::class.simpleName)
        println(e.message)
        println(e.cause?.message)
    }
}
[ann@example.com]
InstanceCreationException
Could not create instance for '[Factory: 'Billing']'
No definition found for type 'PaymentGateway' on scope '['_root_']'.. Check or add definition for type 'PaymentGateway' in scope '_root_'.

The second part shows Koin's main weakness: a missing definition is found only when the object is requested. Add a test that resolves your main types, or use verify() from the koin-test artifact, so these errors show up in CI and not in production.

Compile-time DI: Dagger, Hilt and kotlin-inject

Another family of libraries generates the wiring code at compile time from annotations:

The generated code is essentially the hand-written AppContainer from above. Pick a compile-time library for large Android apps, Koin for a light runtime DSL (and multiplatform), and manual wiring for small and medium programs where adding a library doesn't pay off.

Context parameters

Some dependencies, such as a logger, a transaction or a security context, are needed by many functions down a call chain. Passing them through every parameter list is noisy. Kotlin's context parameters declare them as an implicit part of the function signature:

interface Logger { fun log(msg: String) }

class PrefixLogger(private val prefix: String) : Logger {
    override fun log(msg: String) = println("$prefix $msg")
}

interface Transaction { fun execute(sql: String) }

context(logger: Logger, tx: Transaction)
fun transfer(from: String, to: String, amount: Int) {
    logger.log("transfer $amount from $from to $to")
    tx.execute("update accounts set balance = balance - $amount where id = '$from'")
    tx.execute("update accounts set balance = balance + $amount where id = '$to'")
}

context(logger: Logger)
fun audit(event: String) = logger.log("audit: $event")

fun main() {
    val tx = object : Transaction {
        override fun execute(sql: String) = println("  SQL: $sql")
    }
    with(PrefixLogger("[bank]")) {
        context(tx) {
            transfer("alice", "bob", 50)
        }
        audit("done")
    }
}
[bank] transfer 50 from alice to bob
  SQL: update accounts set balance = balance - 50 where id = 'alice'
  SQL: update accounts set balance = balance + 50 where id = 'bob'
[bank] audit: done

transfer can only be called where a Logger and a Transaction are in scope, from with(...), the context(...) function or an enclosing function with the same context. The compiler checks this, and tests just supply different values. Context parameters were added as a preview in Kotlin 2.2 (with the -Xcontext-parameters flag); this example compiles without flags on Kotlin 2.4. They replace the older experimental context receivers.

Use them for cross-cutting values that flow through a call chain. Services that a class uses throughout its life still belong in the constructor.

Common mistakes

Field injection with lateinit. Frameworks that set fields after construction make it possible to use an object before its dependencies are there:

class Engine
class Car {
    lateinit var engine: Engine
    fun start() = println("starting with $engine")
}
fun main() {
    Car().start()
}
Exception in thread "main" kotlin.UninitializedPropertyAccessException: lateinit property engine has not been initialized
	at Car.getEngine(e7.kt:3)
	at Car.start(e7.kt:4)

Constructor injection makes this state impossible. Use lateinit field injection only when a framework creates the object for you (Android activities and fragments with Hilt's @Inject lateinit var).

Too many constructor parameters. A class that needs eight dependencies does too much. DI didn't cause the problem, it just made it visible. Split the class.

Injecting the container. Passing AppContainer or Koin into a class so it can fetch whatever it wants hides its real dependencies again. Pass the specific things it needs.

Circular dependencies. A needs B and B needs A. With constructors this can't even be expressed, and containers report it at runtime (like the A -> B -> A error above). Usually a third class should own the shared logic, or one side should depend on an interface or a callback instead.

Interfaces for everything. An interface earns its place when there's more than one implementation, including a test fake. A pure helper class with no I/O can be injected as a concrete class, or not injected at all.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents