14
ProAndroidDev
作者:Artem Khmelev
發布:07-08 23:06
Hand-wired DI in Kotlin Multiplatform: a composition root instead of a framework
A KMP app can wire its dependency graph in plain Kotlin — no reflection, no code generation, no annotations, no DSL.
重點摘要
Composition root and constructors make dependencies explicit and testable.
The container hierarchy mirrors the KMP source-set tree and platform boundaries.
Manual DI stays transparent, low-overhead, and easy to migrate if a framework is later needed.
This article argues for hand-wired dependency injection in Kotlin Multiplatform as a practical alternative to heavyweight DI frameworks. The core pattern is a composition root: a single place where the object graph is assembled with ordinary Kotlin constructors, keeping dependencies visible, debuggable, and easy to test. The container hierarchy mirrors the KMP source-set tree, with platform-specific leaves for Android, iOS, and Desktop. The author also explains how the approach scales to libraries through Api/Impl splits, how Android can use a provider interface at framework boundaries, and why this style remains especially readable for teammates and AI coding agents. Frameworks still make sense when lifecycle-bound scopes or unloading are needed, but until then, manual DI keeps the code simple and transparent.
Kotlin Multiplatform 中的手写 DI:用组合根替代框架
KMP 应用可以用纯 Kotlin 组装依赖图——无需反射、代码生成、注解或 DSL。
重點摘要
以组合根和构造函数注入让依赖关系清晰、可测试。
容器层级对应 KMP source-set 层级,并按平台能力分层。
手动 DI 保持透明、低开销,必要时也能平滑迁移到框架。
本文主张在 Kotlin Multiplatform 中采用手写 DI,而不是依赖重量级 DI 框架。核心思路是把对象图集中在一个 composition root 中组装,所有组件都通过构造函数接收依赖,使依赖关系保持为普通 Kotlin 代码,便于查看、调试和测试。作者进一步说明,KMP 的容器层级可以映射到 source-set 层级,并在 Android、iOS、Desktop 等平台叶节点补足各自平台 API。文章还讨论了 Api/Impl 拆分、Android 的 provider 模式,以及这种方式对团队成员和 AI 编码代理的可读性。只有当需要作用域、生命周期绑定或卸载能力时,框架才更值得引入。
Kotlin Multiplatform 的手動 DI:以組合根取代框架
KMP 應用可以用純 Kotlin 組裝依賴圖——不需要反射、程式碼生成、註解或 DSL。
重點摘要
以組合根與建構子注入讓依賴關係清楚可見、易於測試。
容器階層對應 KMP source-set 階層,並區分平台差異。
手動 DI 保持透明、低成本,未來若有需要也能平滑遷移到框架。
本文主張在 Kotlin Multiplatform 中採用手動 DI,而不是依賴重量級框架。核心做法是以 composition root 作為唯一的組裝點,所有物件都透過建構子注入,讓依賴圖保持在普通 Kotlin 程式碼中,便於追蹤、除錯與測試。作者進一步說明,KMP 的容器階層可對應 source-set 階層,並在 Android、iOS、Desktop 等平台葉節點處理各自需要的 API。文章也延伸到 Api/Impl 拆分、Android 的 provider 模式,以及這種寫法對團隊成員與 AI coding agent 的可讀性。只有在需要生命週期範圍、scope 管理或卸載機制時,框架才更有價值。