ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Follow publication

Exploring Dependency Injection in Android — Dagger, Koin, and Kodein

Sherry Yuan
ProAndroidDev
Published in
10 min readMay 22, 2020

--

Dagger has been the reigning dependency injection library in Android for a long time, but a few alternatives have appeared recently. I’ve used Dagger and Koin while working at Yelp and Hootsuite in enterprise-scale Android projects, and played around with Kodein in personal projects, and wanted to compare and contrast using the three different libraries.

There’s also a TL;DR section at the bottom of this article with a summary of the pros and cons of each library and links to more resources.

Preamble: Dependency Injection vs Service Locator

One thing to note is out of the three, technically only Dagger uses a dependency injection (DI) pattern; Koin and Kodein are service locators. In the service locator pattern, there’s a service locator class that creates and stores dependencies, then provides them on demand. Classes have control and ask for objects to be injected, whereas in dependency injection, the app has control and proactively injects the required objects into classes. Fundamentally, both patterns tackle the same problem: decoupling classes from concrete dependencies.

Some sample code

Let’s look at an example of injecting a Door object into House classes, then adding instances of the House classes to our main application. This isn’t meant to be a complete setup tutorial, since lots of those exist for all three libraries already, but I’ll provide some links to good existing ones.

Here’s our Door interface and the DoorImpl class that implements it:

Without dependency injection

The House class:

--

--

Published in ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Written by Sherry Yuan

Android engineer @ Cash App (she/her) • Find my sci-fi/fantasy short stories at sherryyuan.substack.com

Responses (1)

Write a response