Android on Kodein — Painless Dependency Injection

Andreas Botzler
2 min readSep 30, 2017

--

I started to work with Kotlin a couple of month ago, recently i heard about Kodein another Dependency Injection Framwork for Android.

Kodein(KOtlin DEpendency INjection) is written in Kotlin.

We all know and maybe love Dagger or Dagger 2 but with Kotlin it’s simpler to inject our dependencies.

How to use it?

I will explain the functionality of Kodein with a simple grocery app.

First of all we need an Application

Our Application has to be KodeinAware and we have to declare a Kodein property, with Kodein we can define our Dependency bindings, it is like an AppModule in Dagger. In this case we bind our Room Database with eagerSingleton, which means we will get the same instance every time and the instance will be created as soon as the Kodein instance is created.

There are more bindings like factory, provider, multiton and so on which are explained here

Using our Bindings

There are several ways to retrieve Bindings which are defined here

We use the Interface Based though we can inherit from a BaseActivity or BaseFragment.

  1. The Fragment implements SupportFragmentInjector
  2. We have to declare the KodeinInjector property
  3. In onCreateView() and onDestroy() initialize and destroy the injector
  4. With the provideOverridingModule() function we can define Module specific bindings, we use it to bind our ViewModels.
  5. we can retrieve a binding with by injector.instance() herefore Kodein uses Delegated Properties.

The parents of such fragments have to be KodeinInjected. That means they have to implement FragmentActivityInjector or something similar.

Thanks for getting this far! I hope you enjoyed this story. If you think it was worth reading, please share it or show your support and more people will benefit from it. And of course, feel free to leave your feedback!

--

--