Koin - Kotlin Dependency Injection

KOIN is a Kotlin dependency injection framework that and its functional power to get things done! No proxy/CGLib, No code generation, No introspection. Just functional Kotlin and DSL magic 😉

KOIN – Functional Kotlin dependency injection framework

It is an open source project to help you write your dependency injection in few lines.
Let’s build an Android app with koin-android module.

You should see : Lottie – Convert Adobe After Effects to Kotlin

Start with an update of your build.gradle:

Check that you have jcenter repository. Add the following gradle dependency for your Android app:

// repository if needed
allprojects {
    repositories {
        jcenter()
    }
}
// Koin for Android
dependencies {
   compile 'org.koin:koin-android:0.2.0'
}

First of all, you need to write a module. A module gathers your components definitions and allows it to be loaded by Koin and injected in your application. Keep in mind, that injection by constructor is the default strategy targeted by Koin.

Define your module

Write a class that extends AndroidModule, overrides the context() function and uses the declareContext function to define a context like below:

class MyModule : AndroidModule() {
    override fun context() =
        declareContext {
      // declare dependency here ...
      provide { createOkHttpClient() }
  }
    }
}

fun createOkHttpClient() : OkHttpClient { //create OkHttpClient ...}
Kotlin Dependency Injection : Define module
Kotlin Dependency Injection : Define module

The AndroidModule is a Koin module class specialized for Android needs: you can get your injections and applicationContext, resources & assets within your dependencies. e.g: I need my server url here.

You must see this : Kotlin with Dagger 2 (Dependency Injection)

Your context is provided by the context() function and described via the declareContext function. This unlocks the Koin DSL:

  • provide { /* component definition */ } declares a component for your Module
  • bind {/* compatible type */} bind a compatible type for provided definition
  • get() inject a component dependency
  • scope {/* scope class */} define or reuse a scope current module’s definitions

AndroidModule also gives you the possibility to retrieve Android specific resources directly in your module context (ApplicationContextResources & Assets). e.g: Get an Android string in your module:

resources.getString(R.string.server_url)

Use KoinApplication to load module

To start your module, you must build it:

val myContext = Koin().init(applicationInstance).build(MyModule())

This will return a KoinContext object. Koin proposes the KoinContextAware interface, to help define and bring your Koin context all over your app. Configure it like below:

class MainApplication : Application(), KoinContextAware {

     /**
     * Koin context
     */
    lateinit var context: KoinContext

    /**
     * KoinContextAware - Retrieve Koin Context
     */
    override fun getKoin(): KoinContext = context

    override fun onCreate() {
        super.onCreate()
        // insert Koin !
        context = Koin().init(this).build(MyModule()) 
        // ...
    }
}

By using KoinContextAware interface, you will be able to use the Koin Android extensions in your Android Application.

Don’t forget to use the init() function to init Android context injection, else you won’t be able to load your modules & extensions. That’s all! You’re ready.

Amazing scrollviewAndroid DiscreteScrollView

Just make injection

Once you have your Koin context, you can inject your components from anywhere (Application, Activity, Fragment) by using by inject<>() function.

Now you can inject the WeatherService class, with by inject() function extension:

class MainActivity : AppCompatActivity() {

    // inject my WeatherService 
    val weatherService by inject<WeatherService>()
    
    ...
}
Kotlin Dependency Injection : Just make injection
Kotlin Dependency Injection : Just make injection

That’s it!

Download Sample code

Dependency injection in just a few lines 🙂 No Proxy, No code generation, No introspection. Just give it a try!

By Tell Me How

It is a technology blog and admin has excellent experience in programming from 5+ year. You can contact us at ceo.tellmehow@gmail.com

Share your thoughts

Leave a Reply

Loading Facebook Comments ...
Loading Disqus Comments ...