Painless Kotlin Dependency Injection
Kotlin Shell
Latest commit 01393fd Oct 5, 2016 @SalomonBrys committed on GitHub Merge pull request #37 from ArthurCaron/patch-1
Few small typos corrected

README.md

KODEIN

Kotlin 1.0 Maven Central Travis MIT License GitHub issues Slack channel Donate

KOtlin DEpendency INjection

Kodein is a very simple and yet very useful dependency retrieval container. it is very easy to use and configure.

Kodein allows you to:

  • Lazily instantiate your dependencies when needed
  • Stop caring about dependency initialization order
  • Easily bind classes or interfaces to their instance or provider
  • Easily debug your dependency bindings and recursions

Kodein does not allow you to:

  • Automatically instantiate your dependencies via injected constructor and reflexivity. For that, you need Guice.
  • Have dependency injection validated at compile time. For that, you need Dagger.

Kodein is a good choice because:

  • It is small, fast and optimized (makes extensive use of inline)
  • It proposes a very simple and readable declarative DSL
  • It is not subject to type erasure (like Java)
  • It integrates nicely with Android
  • It proposes a very kotlin-esque idiomatic API
  • It can be used in plain Java

Example

An example is always better than a thousand words:

val kodein = Kodein {
    bind<Dice>() with provider { RandomDice(0, 5) }
    bind<DataSource>() with singleton { SqliteDS.open("path/to/file") }
}

class Controller(private val kodein: Kodein) {
    private val ds: DataSource = kodein.instance()
}

Read more

Kodein version 3 is the current major version available:

If you are still using Kodein 2, here is the relevant documentation: