koin
Koin is an amazing Dependency Injection Framework for Kotlin and Android projects. It has gained huge popularity over the past two years and many Android developers (including myself) have adopted it, use it in production relying on its powerful mechanism to help perform dependency injection. And we just love it!
Koin是用于Kotlin和Android项目的惊人的依赖注入框架。 在过去的两年中,它已经获得了巨大的普及,许多Android开发人员(包括我自己)已经采用了它,并依靠其强大的机制来帮助进行依赖注入,从而在生产中使用它。 我们就是喜欢它!
We love Koin because it’s simpler than Dagger 2 (we’re not gonna talk about Hilt yet). We find it to be very simple because Koin does a lot of magic tricks under the hood for us and provides a really nice and elegant API for dependency declaration & manipulation.
我们喜欢Koin,因为它比Dagger 2更简单(我们还不会谈论Hilt)。 我们发现它非常简单,因为Koin为我们做了很多魔术,并为依赖项声明和操作提供了一个非常漂亮而优雅的API。
Of course, there is a debate here about if Koin is a real Dependency Injection framework or a Service Locator but we’re not going to spread out on that question in this post.
当然,这里有一个关于Koin是真正的依赖注入框架还是服务定位器的争论,但是在本文中我们将不讨论这个问题。
The goal of this post is to try to replicate something that looks like Koin but with a naive approach. Our DI framework will be inspired by Koin, we will try to achieve the same API and implement our own core logic for dependency management. We will call this unicorn LiteKoin.
这篇文章的目的是尝试以天真的方法复制看起来像Koin的东西。 我们的DI框架将受到Koin的启发,我们将尝试实现相同的API并实现我们自己的依赖关系管理核心逻辑。 我们将其称为独角兽LiteKoin。
This post will be long so make sure you grab a cup of coffee.
这篇文章将很长,因此请确保您抓住一杯咖啡。
To understand what we will be doing here, you must be familiar with these concepts:
要了解我们将在这里做什么,您必须熟悉以下概念:
- Building DSLs in Kotlin (Higher Order Functions, Lambdas with receiver, Extension Functions) 在Kotlin中构建DSL(高阶功能,带接收器的Lambda,扩展功能)
- Kotlin Generics, Operator Overloading, Extension Properties, Kotlin Reflection, Type Aliases Kotlin泛型,运算符重载,扩展属性,Kotlin反射,类型别名
服务定位器 (Service Locator)
We will base our approach on the Service Locator design pattern. This pattern is actually very simple to understand.
我们将以服务定位器设计模式为基础。 这种模式实际上很容易理解。
The service locator pattern is a design pattern used in software development to encapsulate the processes involved in obtaining a service with a strong abstraction layer. This pattern uses a central registry known as the “service locator”, which on request returns the information necessary to perform a certain task. — Wikipedia
服务定位器模式是一种设计模式,用于软件开发,以封装包含具有强大抽象层的服务的过程。 此模式使用一个称为“服务定位器”的中央注册表,该注册表根据请求返回执行特定任务所需的信息。 —维基百科
There are several ways to implement a Service Locator. In our case, we want to identify services by their types. This will help with the reflection part.
有几种方法可以实现服务定位器。 在我们的案例中,我们想通过服务类型来识别它们。 这将有助于反射部分。
服务 (Service)
We start by creating a Service interface.
我们首先创建一个Service接口。
interface