SuperAPI AI 工具集

dependency injection setup

编程与开发

查看项目

更新于 10-16 04:26

技能介绍

用途

该技能用于在 Leavn 应用的 DIContainer 中添加新服务,并按照基于协议的依赖注入(Dependency Injection)方式组织代码。它适用于创建新服务、添加依赖、搭建依赖注入,或重构为面向协议设计的场景。

主要能力

技能提供了一套标准步骤,用于:

  1. 创建服务协议;
  2. 创建协议的具体实现;
  3. 在 DIContainer 中注册服务,可选择单例或工厂模式;
  4. 在 ViewModel 中使用该服务。

使用方式

1. 创建服务协议

在 Services/MyDomain/MyServiceProtocol.swift 中定义协议:

public protocol MyServiceProtocol {
    func doSomething() async throws -> Result
}

2. 创建实现

在 Services/MyDomain/MyServiceLive.swift 中实现协议:

public final class MyServiceLive: MyServiceProtocol {
    public init() { }

    public func doSomething() async throws -> Result {
        // Implementation
    }
}

3. 在 DIContainer 中注册

对于有状态的服务,使用单例方式:

private lazy var _myService = MyServiceLive()
var myService: MyServiceProtocol {
    _myService
}

对于无状态的服务,使用工厂方式:

var myService: MyServiceProtocol {
    MyServiceLive()
}

4. 在 ViewModel 中使用

let service = DIContainer.shared.myService

适用场景

  • 创建新服务
  • 添加依赖
  • 搭建依赖注入
  • 重构为面向协议设计

限制

资料中未提供关于该技能的其他限制、收费、价格、平台或效果信息。