Dependency Injection and Service Locator are the two main methods to implement Inversion of Control.

Android’s leading dependency injection frameworks include: Dagger and Kion

These dependency injection frameworks all feel heavy.

Service locator such as rare, here provides a simple implementation of the service locator pattern.

The introduction of

Project address: github.com/czy1121/ser…

repositories { 
    maven { url "https://gitee.com/ezy/repo/raw/android_public/"}
} 
dependencies {
    implementation "Me. Reezy. Jetpack: the servicelocator: 0.4.0" 
}
Copy the code

API

// Get the instance
inline fun <reified T> resolve(name: String = T::class.java.name): T?
// Register as a singleton
inline fun <reified T> singleton(name: String = T::class.java.name.crossinline block: () -> T)
// Register as factory
inline fun <reified T> factory(name: String = T::class.java.name.crossinline block: () -> T)
Copy the code

use

Singleton. Resolve obtains the same instance each time

class SomeService {
    fun doSomething(a){}}/ / register
singleton {
    SomeService()
}

/ / to get
val service = resolve<SomeService>() 
Copy the code

With a list of cases

class NamedService(val name: String) {
    fun doSomething(a){}}/ / register
singleton("a") {
    NamedService("aaa")
}
singleton("b") {
    NamedService("bbb")}/ / to get
val serviceA = resolve<NamedService>("a")
val serviceB = resolve<NamedService>("b")
Copy the code

Factory, each time resolve generates a new instance

class SomeService {
    fun doSomething(a){}}/ / register
factory {
    SomeService()
}

Resolve generates a new instance each time
val service1 = resolve<SomeService>() 
val service2 = resolve<SomeService>() 
Copy the code

To be the factory

class NamedService(val name: String) {
    fun doSomething(a){}}/ / register
factory("a") {
    NamedService("aaa")
}
factory("b") {
    NamedService("bbb")}/ / to get
// A1 and A2 are different instances using the same factory
// A1 and B1 are different instances generated using different factories
val serviceA1 = resolve<NamedService>("a")
val serviceA2 = resolve<NamedService>("a")
val serviceB1 = resolve<NamedService>("b")
val serviceB2 = resolve<NamedService>("b")
Copy the code