DI with Koin, Introduction and Implementation: (Part -1).

Mirza Adil
2 min readJul 8, 2021

--

part-1 we should focus on Introduction & pros and cons of DI.

It is a smart Kotlin Dependency Injection Library as compare Dagger 2.

Its features are:

  • Light weight.
  • Easy to learn.
  • Does not have much boilerplate code.
  • It supports the Kotlin DSL feature.

Why we are used DI?

So what are the pros and cons of using DI in your project?

To help you with the answer, take a look at the SOLID principles of object-oriented programming, which are five principles that improve the reusability of code and reduce need to refactor any class.

DI is directly related with two of pillars, specifically

Single Responsibility Principle and Dependency Inversion.

Briefly explained

  • Single Responsibility Principle states that every class or module in a program is responsible for just a single piece of that program’s functionality.
  • Dependency Inversion states that high level modules should not depend on low level modules; both should depend on abstractions.

DI supports these goals by decoupling the creation and the usage of an object. Thus, it allows you to replace dependencies without changing the class that uses them and also reduces the risk of modifying a class because one of its dependencies changed.

This makes DI a great option when an application is expected to grow considerably in size and/or complexity.

So, why use Koin rather than one of the other DI frameworks?

The answer:

Koin is more concise and straightforward than the others DI.

Take the popular Dagger 2 as an example.

To use Dagger 2, you first need to become familiar with concepts like module and component and annotations such as @Inject. While the steep learning curve for this framework eventually pays off, to get the most out of it, you still have to learn some advanced concepts such as scope and subcomponents.

In contrast, Koin allows you to simply declare modules, which include potential dependencies, to be used in the project and directly inject them in the class of interest.

Koin Terminology:

  • module : it creates a module in Koin which would be used by Koin to provide all the dependencies.
  • single: it creates a singleton that can be used across the app as a singular instance.
  • factory : it provides a bean definition, which will create a new instance each time it is injected.
  • get(): it is used in the constructor of a class to provide the required dependency.

--

--

Mirza Adil
Mirza Adil

Written by Mirza Adil

Technical Lead Android & Solution Architecture

No responses yet