DEV Community

Robertino
Robertino

Posted on

💻 Dependency Injections with Koin

📙 Learn how to implement common dependency injection scenarios with Koin and Kotlin.


Inversion of Control (IoC) is a broad term to describe how responsibility for some aspect of a system is lifted out of the custom code written by the end developer and into a framework. Martin Fowler describes a framework in terms of IoC:

Inversion of Control is a key part of what makes a framework different from a library. A library is essentially a set of functions that you can call, these days usually organized into classes. Each call does some work and returns control to the client.

A framework embodies some abstract design, with more behavior built-in. In order to use it, you need to insert your behavior into various places in the framework, either by subclassing or by plugging in your own classes. The framework's code then calls your code at these points.

Dependency injection (DI) is one specific example of IoC where classes no longer directly instantiate member properties by creating new objects but instead declare their dependencies and allow an external system, in this case, a dependency injection framework to satisfy those dependencies.

Koin is a dependency injection framework for Kotlin. It is lightweight, can be used in Android applications, is implemented via a concise DSL, and takes advantage of Kotlin features like delegate properties rather than relying on annotations.

In this post, we'll look at a simple application taking advantage of Koin to inject dependencies into our custom classes.

Prerequisites

To build the sample application, you'll need to have JDK 11 or above, which is available from many sources, including OpenJDK, AdoptOpenJDK, Azul, or Oracle.

The code for the sample Koin application can be found here.

The Gradle Project Definition

We start with the Gradle build file, which includes dependencies for Kotlin and Koin, and makes use of the shadow plugin to create self-contained uberjars:

buildscript {
    repositories {
        maven {
            url "https://plugins.gradle.org/m2/"
        }
    }
    dependencies {
        classpath 'com.github.jengelman.gradle.plugins:shadow:6.1.0'
    }
}

plugins {
    id "org.jetbrains.kotlin.jvm" version "1.5.21"
}

apply plugin: 'kotlin'
apply plugin: 'com.github.johnrengelman.shadow'

repositories {
    mavenLocal()
    mavenCentral()
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib:1.5.21"
    implementation "io.insert-koin:koin-core:3.1.2"
}
Enter fullscreen mode Exit fullscreen mode

To build the uberjar, run this command from Bash or PowerShell:

./gradlew shadowJar
Enter fullscreen mode Exit fullscreen mode

Read more...

Discussion (0)