arkdi:基于 HarmonyOS ArkTS 的依赖注入框架项目

一个适用于ArkTS的轻量级依赖注入库

Branch1Tags0
FilesLast commitLast update
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago

ArkDI

ArkDI 是一个为 HarmonyOS ArkTS设计的轻量级依赖注入(DI)框架,灵感来自 Android 的 Koin。它提供纯 ArkTS 实现的 DSL 风格 API,帮助开发者在 ArkUI 应用中管理依赖关系、作用域生命周期和 ViewModel 注入。

为什么需要 ArkDI

ArkUI 中的依赖管理痛点

HarmonyOS ArkUI 采用声明式 UI 框架,组件之间经常需要共享服务(网络请求、数据仓库、配置管理等)。常见做法是:

// ❌ 手动创建,紧耦合
const apiClient = new ApiClient('https://api.example.com')
const userRepo = new UserRepository(apiClient)
const viewModel = new UserViewModel(userRepo)

这种做法的问题:

  • 依赖关系硬编码 — 改一个构造参数要改 N 处
  • 生命周期难控制 — 单例?每次新建?作用域内复用?
  • 测试困难 — 无法方便地替换为 Mock
  • 组件间重复创建 — 多个页面各自 new 同一个服务

ArkDI 的解决方案

ArkDI 用声明式的方式注册依赖,按需解析,自动管理生命周期:

// ✅ 声明依赖关系
const appModule = module()
  .single(ApiClient, () => new ApiClient('https://api.example.com'))
  .single(UserRepository, (r) => new UserRepository(r.get(ApiClient)))
  .scoped(UserViewModel, (r) => new UserViewModel(r.get(UserRepository)))

// 在 UIAbility 中启动
startArkDI({ modules: [appModule] })

// 在组件中注入
@State vm: UserViewModel = inject(UserViewModel)

特性一览

特性 说明
三种生命周期 single(单例)、factory(每次新建)、scoped(作用域内复用)
模块化 DSL module().single().factory().scoped() 链式声明
命名限定符 同一类型注册多个实现,用 named() 区分
参数化注入 parametersOf() 在解析时传递运行时参数
接口绑定 boundTypes 将实现类绑定到抽象类 token
集合注入 getAll<T>() 获取同一 token 下的所有注册实例
作用域管理 创建/关闭/链接作用域,自动生命周期回调
属性配置 startArkDI({ properties }) 注入配置值
懒加载模块 LazyModule 延迟加载重型模块
装饰器支持 @Injectable + @Inject(需 reflect-metadata)
测试支持 declareMock()、overrideModule()、verify()
循环依赖检测 自动检测并抛出 CircularDependencyError
解析追踪 setTraceEnabled(true) 调试依赖解析链
Eager 创建 eager: true 在启动时立即实例化

快速开始

1. 安装

将 arkdi 模块添加到你的 HarmonyOS 项目中:

// entry/oh-package.json5
{
  "dependencies": {
    "arkdi": "file:../arkdi"
  }
}

2. 定义服务类

// services/ApiClient.ets
export class ApiClient {
  private baseUrl: string
  constructor(baseUrl: string) {
    this.baseUrl = baseUrl
  }
  public async request(path: string): Promise<string> {
    return `${this.baseUrl}${path}`
  }
}

// services/UserRepository.ets
export class UserRepository {
  private apiClient: ApiClient
  constructor(apiClient: ApiClient) {
    this.apiClient = apiClient
  }
  public async getUsers(): Promise<string[]> {
    return ['Alice', 'Bob']
  }
}

// services/UserViewModel.ets
@Observed
export class UserViewModel {
  public users: string[] = []
  public loading: boolean = false
  private repo: UserRepository

  constructor(repo: UserRepository) {
    this.repo = repo
  }

  async loadUsers(): Promise<void> {
    this.loading = true
    this.users = await this.repo.getUsers()
    this.loading = false
  }
}

3. 声明 DI 模块

// di/AppModule.ets
import { module } from 'arkdi'
import { ApiClient } from '../services/ApiClient'
import { UserRepository } from '../services/UserRepository'
import { UserViewModel } from '../services/UserViewModel'

export const networkModule = module()
  .single(ApiClient, () => new ApiClient('https://api.example.com'))

export const userModule = module()
  .single(UserRepository, (r) => new UserRepository(r.get(ApiClient)))
  .scoped(UserViewModel, (r) => new UserViewModel(r.get(UserRepository)))

4. 启动 ArkDI

// entryability/EntryAbility.ets
import { startArkDI, stopArkDI, ConsoleLogger } from 'arkdi'
import { networkModule, userModule } from '../di/AppModule'

export default class EntryAbility extends UIAbility {
  onCreate(): void {
    startArkDI({
      modules: [networkModule, userModule],
      logger: new ConsoleLogger()
    })
  }

  onDestroy(): void {
    stopArkDI()
  }
}

5. 在 UI 中注入

// pages/Index.ets
import { inject } from 'arkdi'
import { UserViewModel } from '../services/UserViewModel'

@Entry
@Component
struct Index {
  @State vm: UserViewModel = inject<UserViewModel>(UserViewModel)

  build() {
    Column() {
      Button('加载用户')
        .onClick(() => this.vm.loadUsers())

      if (this.vm.loading) {
        LoadingProgress().margin({ top: 20 })
      }

      ForEach(this.vm.users, (name: string) => {
        Text(name).fontSize(16).padding(8)
      }, (name: string, index: number) => `${index}`)
    }
    .width('100%')
    .height('100%')
  }
}

详细用法

三种生命周期

import { module } from 'arkdi'

const myModule = module()
  // 单例:全局只创建一次,后续 get() 返回同一实例
  .single(ConfigService, () => new ConfigService())

  // 工厂:每次 get() 都创建新实例
  .factory(RequestContext, () => new RequestContext())

  // 作用域:在同一 Scope 内复用,不同 Scope 各自独立
  .scoped(UserViewModel, (r) => new UserViewModel(r.get(UserRepository)))
生命周期 创建时机 缓存位置 适用场景
single 首次 get() 时 ArkDI 容器 配置、网络客户端、数据库
factory 每次 get() 时 无 请求上下文、临时对象
scoped Scope 内首次 get() 时 Scope 实例 ViewModel、页面级状态

命名限定符

当同一类型需要注册多个实现时,用 named() 区分:

import { module, named } from 'arkdi'

const loggerModule = module()
  .single(Logger, () => new ConsoleLogger(), named('console'))
  .single(Logger, () => new FileLogger('/var/log/app.log'), named('file'))

// 解析时指定限定符
const consoleLogger = di.get<Logger>(Logger, named('console'))
const fileLogger = di.get<Logger>(Logger, named('file'))

参数化注入

在解析时传递运行时参数给工厂函数:

import { module, parametersOf } from 'arkdi'

const vmModule = module()
  .factory(UserDetailVM, (r) => {
    const params = r.getParameters()
    const userId = params[0] as string
    return new UserDetailVM(userId, r.get(UserRepository))
  })

// 解析时传入参数
const vm = di.get<UserDetailVM>(UserDetailVM, undefined, parametersOf('user_123'))

要点:

  • 参数通过 resolver.getParameters() 在工厂函数中获取
  • 参数不穿透:子依赖无法访问父级参数
  • 单例首次创建使用传入参数,后续忽略

接口绑定

将实现类绑定到抽象类 token,通过抽象类解析:

import { module } from 'arkdi'

// 注意:ArkTS 中 interface 不能作为值使用,需用 abstract class
abstract class IAuthService {
  abstract login(user: string, pass: string): boolean
}

class AuthServiceImpl extends IAuthService {
  login(user: string, pass: string): boolean {
    return user === 'admin' && pass === '123456'
  }
}

const authModule = module()
  .single(AuthServiceImpl, (r) => new AuthServiceImpl(), { boundTypes: [IAuthService] })

// 通过抽象类 token 解析
const auth = di.get<IAuthService>(IAuthService) // 返回 AuthServiceImpl 实例

// 通过实现类 token 也能解析,且是同一个单例
const impl = di.get<AuthServiceImpl>(AuthServiceImpl)
// auth === impl → true

集合注入

获取同一 token 下所有注册的实例:

import { module, getAll, named } from 'arkdi'

const pluginModule = module()
  .single(Plugin, () => new AnalyticsPlugin(), named('analytics'))
  .single(Plugin, () => new CrashPlugin(), named('crash'))
  .single(Plugin, () => new PerformancePlugin(), named('perf'))

// 获取所有 Plugin 实例
const allPlugins: Plugin[] = getAll<Plugin>(Plugin)

作用域管理

基本用法

import { getArkDI } from 'arkdi'

const di = getArkDI()

// 创建作用域
const userScope = di.createScope('user_session')

// 在作用域中解析(同一 Scope 内返回同一实例)
const vm1 = userScope.get<UserViewModel>(UserViewModel)
const vm2 = userScope.get<UserViewModel>(UserViewModel)
// vm1 === vm2 → true

// 关闭作用域(触发 onReleased 生命周期 + onClose 回调)
userScope.close()

作用域链接

子作用域可以访问父作用域中已缓存的 scoped 实例:

const parentScope = di.createScope('page_session')
const childScope = di.createScope('component')

// 链接:child 可以看到 parent 中已缓存的 scoped 实例
childScope.linkTo(parentScope)

// 如果 ParentViewModel 在 parentScope 中已缓存
// childScope 也能获取到同一个实例

作用域关闭回调

const scope = di.createScope('temp')

scope.onClose((scopeId: string) => {
  console.info(`Scope ${scopeId} is closing, cleanup resources`)
})

scope.close() // 触发回调

属性配置

在 startArkDI 时注入配置值,在工厂函数中读取:

import { startArkDI, getProperty } from 'arkdi'

startArkDI({
  modules: [appModule],
  properties: {
    'api.base_url': 'https://api.example.com',
    'app.version': '1.0.0',
    'debug.mode': 'true'
  }
})

// 在工厂函数中读取
const configModule = module()
  .single(ApiClient, (r) => {
    const baseUrl = r.getProperty('api.base_url')
    return new ApiClient(baseUrl)
  })

// 全局读取
const version = getProperty('app.version')       // '1.0.0'
const missing = getProperty('missing.key', '默认值') // '默认值'

Eager 创建

标记为 eager: true 的定义会在 startArkDI 时立即实例化,而非等到首次 get():

const appModule = module()
  .single(DatabaseService, () => new DatabaseService(), { eager: true })
  .single(CacheService, () => new CacheService(), { eager: true })

// startArkDI 时 DatabaseService 和 CacheService 立即创建
startArkDI({ modules: [appModule] })

生命周期回调

监听实例的创建和释放:

import { module, type LifecycleCallbacks } from 'arkdi'

const lifecycle: LifecycleCallbacks = {
  onCreated: (instance: Object) => {
    console.info('Service created')
  },
  onReleased: (instance: Object) => {
    console.info('Service released, cleanup resources')
  }
}

const appModule = module()
  .single(DatabaseService, () => new DatabaseService(), { lifecycle: lifecycle })
回调 触发时机 适用场景
onCreated 实例创建后 初始化日志、注册观察者
onReleased 实例从缓存移除时 关闭连接、释放资源

ArkUI 状态管理集成

ArkDI 注入的实例可直接搭配 ArkUI 状态管理使用:

V1 — @Observed + @State:

@Observed
class CounterVM {
  public count: number = 0
}

@Component
struct CounterPage {
  @State vm: CounterVM = inject<CounterVM>(CounterVM)

  build() {
    Button(`Count: ${this.vm.count}`)
      .onClick(() => this.vm.count++)
  }
}

V2 — @ObservedV2 + @Trace + @Local:

@ObservedV2
class CounterVM {
  @Trace count: number = 0
}

@ComponentV2
struct CounterPage {
  @Local vm: CounterVM = inject<CounterVM>(CounterVM)

  build() {
    Button(`Count: ${this.vm.count}`)
      .onClick(() => this.vm.count++)
  }
}

无装饰器类 — makeObserved 运行时加观察:

对于无法添加 @ObservedV2 的类(三方包、@Sendable 类、JSON.parse 对象),可在组件中用 UIUtils.makeObserved 包装:

import { UIUtils } from '@kit.ArkUI'

// 三方包的类,无法加装饰器
class ThirdPartyModel {
  public value: number = 0
}

@ComponentV2
struct MyPage {
  @Local model: ThirdPartyModel = UIUtils.makeObserved(inject<ThirdPartyModel>(ThirdPartyModel))

  build() {
    Button(`Value: ${this.model.value}`)
      .onClick(() => this.model.value++)
  }
}

提示: makeObserved 仅对未加 @ObservedV2 的类生效,已加装饰器的类会自动跳过,无副作用。

模块组合

import { module } from 'arkdi'

const dataModule = module()
  .single(ApiClient, () => new ApiClient())
  .single(Database, () => new Database())

const domainModule = module()
  .single(UserRepository, (r) => new UserRepository(r.get(ApiClient), r.get(Database)))

// include 组合多个模块
const appModule = module()
  .include(dataModule, domainModule)
  .single(UserViewModel, (r) => new UserViewModel(r.get(UserRepository)))

// 同一模块实例多次 include 只生效一次(自动去重)
const combined = module().include(appModule, dataModule) // dataModule 不会重复注册

懒加载模块

重型模块延迟到首次使用时才加载:

import { module, lazyModule } from 'arkdi'

const heavyModule = lazyModule(() => {
  // 这些定义在首次 inject 前不会执行
  return module()
    .single(HeavyService, () => new HeavyService())
    .single(AnotherService, () => new AnotherService())
})

startArkDI({ modules: [lightModule, heavyModule] })
// heavyModule 的工厂函数在首次 inject(HeavyService) 时才执行

动态加载/卸载模块

const di = getArkDI()

// 运行时加载新模块
di.loadModule(featureModule)

// 运行时卸载模块
di.unloadModule(featureModule)

解析追踪

调试时开启解析日志,查看依赖解析链:

const di = startArkDI({ modules: [appModule] })
di.setTraceEnabled(true)

// 所有 get() 调用会输出类似:
// [ArkDI] → resolve: UserRepository
// [ArkDI]   → resolve: ApiClient
// [ArkDI]   ← resolved: ApiClient
// [ArkDI] ← resolved: UserRepository

循环依赖检测

ArkDI 自动检测循环依赖并抛出明确的错误信息:

// A → B → A 会触发
const badModule = module()
  .single(ServiceA, (r) => new ServiceA(r.get(ServiceB)))
  .single(ServiceB, (r) => new ServiceB(r.get(ServiceA)))

di.get(ServiceA)
// CircularDependencyError: Circular dependency detected: ServiceA -> ServiceB -> ServiceA

装饰器 API(实验性)

基于 reflect-metadata 的装饰器支持,提供声明式依赖注入:

import 'reflect-metadata'
import { Injectable, Inject, module } from 'arkdi'

@Injectable({ scope: 'single' })
class ConfigService {
  getApiUrl(): string { return 'https://api.example.com' }
}

@Injectable({ scope: 'single' })
class UserService {
  @Inject(ConfigService)
  private config!: ConfigService

  getUsers(): string[] {
    return ['Alice', 'Bob']
  }
}

// 使用 module().register() 注册,装饰器元数据自动处理
const decoratedModule = module()
  .register(ConfigService, () => new ConfigService())
  .register(UserService, () => new UserService())

注意: 装饰器功能依赖 reflect-metadata 库,HarmonyOS 环境需确保该库已安装。


测试支持

declareMock — 动态替换单个依赖

import { startArkDI, getArkDI, declareMock } from 'arkdi'

// 正常启动
startArkDI({ modules: [appModule] })

// 在测试中替换为 Mock
const mockRepo = new MockUserRepository()
getArkDI()!.declareMock(UserRepository, () => mockRepo)

// 之后所有 get(UserRepository) 返回 mockRepo
// 原始定义的 kind(single/factory/scoped)被保留

overrideModule — 模块级覆盖

const mockModule = module()
  .single(ApiClient, () => new MockApiClient())
  .single(UserRepository, () => new MockUserRepository())

getArkDI()!.overrideModule(mockModule)

verify — 依赖图校验

const di = startArkDI({ modules: [appModule] })
const errors = di.verify()

if (errors.length === 0) {
  console.info('所有依赖可正常解析')
} else {
  for (const err of errors) {
    console.error(`解析失败: ${err.token}${err.qualifier ? '::' + err.qualifier : ''} - ${err.error}`)
  }
}

verify() 不会破坏已存在的单例实例。


API 参考

全局函数

函数 签名 说明
startArkDI (config: ArkDIConfig) => ArkDI 初始化 DI 容器
stopArkDI () => void 销毁全局容器
getArkDI () => ArkDI | null 获取全局容器
inject <T>(token, qualifier?, params?) => T 解析依赖(全局快捷方式)
injectOrNull <T>(token, qualifier?, params?) => T | null 安全解析,不存在返回 null
getAll <T>(token) => T[] 获取同 token 所有实例
getProperty (key, defaultValue?) => string 获取配置属性
named (name: string) => string 创建命名限定符
parametersOf (...args: Object[]) => Object[] 创建注入参数
module () => Module 创建模块
lazyModule (factory: () => Module) => LazyModule 创建懒加载模块

ArkDI 类

方法 说明
get<T>(token, qualifier?, params?) 解析依赖
getOrNull<T>(token, qualifier?, params?) 安全解析
inject<T>(token, qualifier?) 返回 Lazy<T>
getAll<T>(token) 集合注入
getProperty(key, defaultValue?) 读取配置
setProperty(key, value) 设置配置
createScope(id) 创建作用域
getScope(id) 获取已有作用域
deleteScope(id) 删除作用域
loadModule(mod) 加载模块
unloadModule(mod) 卸载模块
overrideModule(mod) 测试:覆盖模块
declareMock<T>(token, factory, qualifier?) 测试:声明 Mock
verify() 测试:校验依赖图
setTraceEnabled(enabled) 开关解析追踪
close() 关闭容器

ArkDIConfig

interface ArkDIConfig {
  modules: Module[]                // DI 模块列表
  logger?: Logger                  // 日志实现(默认 EmptyLogger)
  allowOverride?: boolean          // 允许覆盖注册(默认 false)
  properties?: Record<string, string>  // 配置属性
}

Module DSL

module()
  .single<T>(token, factory, options?)
  .factory<T>(token, factory, options?)
  .scoped<T>(token, factory, options?)
  .register<T>(token, factory, options?)
  .include(...modules)

// options: RegisterOptions
interface RegisterOptions {
  qualifier?: string            // 命名限定符
  lifecycle?: LifecycleCallbacks // 生命周期回调
  boundTypes?: Object[]          // 接口绑定
  eager?: boolean                // 启动时立即创建
}

Scope 类

方法 说明
get<T>(token, qualifier?, params?) 作用域内解析
getOrNull<T>(token, qualifier?, params?) 安全解析
inject<T>(token, qualifier?) 返回 Lazy<T>
getAll<T>(token) 集合注入
linkTo(parent) 链接父作用域
onClose(callback) 注册关闭回调
close() 关闭作用域
get isClosed 是否已关闭

错误类型

错误类 说明
DependencyNotFoundError 依赖未注册
CircularDependencyError 循环依赖(含 dependencyChain)
OverrideNotAllowedError 重复注册且未开启 allowOverride
ScopeAlreadyClosedError 访问已关闭的作用域

架构设计

┌──────────────────────────────────────────┐
│                  ArkDI                    │
│  (DI 容器,全局入口)                       │
│                                          │
│  ┌──────────┐  ┌──────────┐  ┌────────┐ │
│  │ Registry │  │ Resolver │  │ Scopes │ │
│  │ 注册表    │  │ 解析引擎  │  │ 作用域  │ │
│  └──────────┘  └──────────┘  └────────┘ │
│       ▲             ▲                     │
│       │             │                     │
│  ┌────┴─────────────┴────┐               │
│  │      Definition       │               │
│  │  (依赖定义数据类)       │               │
│  └───────────────────────┘               │
│       ▲                                  │
│       │                                  │
│  ┌────┴──────────┐                       │
│  │    Module      │                       │
│  │  (DSL 注册器)  │                       │
│  └───────────────┘                       │
└──────────────────────────────────────────┘

核心组件:

  • Registry — 二级 Map 存储(Map<Object, Map<string, Definition>>),支持接口绑定别名
  • Resolver — 解析引擎,管理单例缓存、参数栈、循环依赖检测
  • Scope — 作用域实例缓存,支持链接和生命周期回调
  • Module — DSL 注册器,支持组合和去重

ArkTS 平台约束

ArkDI 针对 ArkTS 的严格限制做了以下设计决策:

限制 ArkDI 的处理方式
类引用不能直接作为值 使用 Object 类型接收类引用,触发预期警告
不支持 structural typing 所有类型使用 class/abstract class 定义
throw 只能抛出 Error 自定义错误全部继承 Error
不支持索引访问 obj[key] 提供 getRegistry()/getResolver() 公共方法
interface 不能作为值 接口绑定使用 abstract class 替代 interface

与 Koin 的对比

功能 Koin (Android) ArkDI (HarmonyOS)
注册 DSL module { single { ... } } module().single(Token, () => ...)
Token 类型 Reified 泛型 类引用 Object
单例 single { } single(token, factory)
工厂 factory { } factory(token, factory)
作用域 scope<ScopeID> { scoped { } } scoped(token, factory) + createScope()
命名限定符 named("xxx") named("xxx")
参数化 parametersOf() parametersOf()
接口绑定 bind<Interface>() boundTypes: [IFoo]
集合注入 getAll() getAll()
模块组合 includes include()
测试 Mock declareMock declareMock
依赖校验 verify() verify()
装饰器 无 @Injectable + @Inject

项目结构

arkdi/                         # HAR 库模块
  Index.ets                    # 公共 API 导出
  src/main/ets/
    api/Koin.ets               # 主入口:ArkDI 类 + 全局函数
    core/
      Types.ets                # 核心接口和类型
      Definition.ets           # 依赖定义数据类
      Registry.ets             # 注册表
      Resolver.ets             # 解析引擎
      Scope.ets                # 作用域管理
      Module.ets               # 模块 DSL
      Lazy.ets                 # 懒加载包装
      LazyModule.ets           # 懒加载模块
      Qualifier.ets            # 限定符工具
      Logger.ets               # 日志接口
      Errors.ets               # 自定义错误
      Decorators.ets           # 装饰器系统
    integration/ComponentExt.ets  # ArkUI 集成
entry/                         # 示例/测试应用

License

MIT

Introduction

一个适用于ArkTS的轻量级依赖注入库

Customize your domain