5

GitHub - kotlinize/injection: Lightweight Dependency Injection solution for Kotl...

 1 year ago
source link: https://github.com/kotlinize/injection
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Kotlin Dependency Injection Library

Simple, Lightweight Dependency Injection solution for Kotlin / Android(Kotlin) that reduces boiler-plate code used in most Dependency Injection Solutions.

Table of contents

Introduction and references

An example of how to Setup and register objects into the Dependency com.kotlinizer.injection.Injector.

A good practice is to initialize the Dependency com.kotlinizer.injection.Injector in the early Lifecycle Stages, such as the onCreate() method of the Application.

import android.app.Application
import com.kotlinizer.injection.*

class MainApplication : Application() {
	
	private val injector: Injector by lazy { Injector.instance }
	override fun onCreate() {
		super.onCreate()
		
		// Load Dependencies
		val firstName = "Kotlin"
		val lastName = "Dependency-Injection"
		val phoneNumber = 5555555555L
		
		injector.register(type = String::class.java, provider = firstName, identifier = "FIRST_NAME")
		injector.register(type = String::class.java, provider = lastName, identifier = "LAST_NAME")
		injector.register(type = Long::class.java, provider = phoneNumber)
		
	}
}

An example of how to retrieve, or resolve, the object from the Dependency.

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.kotlinizer.injection.*

class MainActivity : AppCompatActivity() {
	private val injector: Injector by lazy { Injector.instance }
	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_main)
		// Retrieve the data from the Dependency com.kotlinizer.injection.Injector.
		val firstName: String? = injector.resolve(type = String::class.java, identifier = "FIRST_NAME")
		val lastName: String? = injector.resolve(type = String::class.java, identifier = "LAST_NAME")
		// No identifier is passed, as we didn't use one when being registered.
		val phoneNumber: Long? = injector.resolve(type = Long::class.java)
	}
}

Full example can be found here

In Action:

Dependency%20Injection%20Example.gif

Setup

To setup, simply add this dependency to your project and everything should be ready to go!

Kotlin DSL

dependencies {
    implementation("com.kotlinizer:injection:1.0.4")
}

Groovy DSL

dependencies {
    implementation 'com.kotlinizer:injection:1.0.4'
}

Maven

<dependency>
    <groupId>com.kotlinizer</groupId>
    <artifactId>injection</artifactId>
    <version>1.0.4</version>
</dependency>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK