LightIoC 1.3.1

LightIoC 1.3.1

Ondrej Pisin 维护。



LightIoC 1.3.1

LightIoC

Swift 的 Light IoC 容器。

CI Status Codecov Version License Platform Swift

LightIoC 是一个易于使用的依赖注入(DI)框架,用于 Swift,并实现自动依赖注入。它管理对象的创建和生命周期,并且将依赖注入到类中。IoC 容器创建一个指定类的一个对象,并在运行时通过属性注入所有依赖对象。这样,您就不必手动创建和管理对象了。

为什么要使用 DI

DI 指导您创建 SOLID 应用程序。

  • 在您的类背后使用协议,这样它们就容易被测试,只需更改 Test 项目的模块注册并使用模拟类即可。
  • 不要隐藏类的依赖关系,您可以通过类和 @Dependency 语法识别所有依赖。
  • 您不必再使用 class.shared.func 语法来编写单例了,将类注册为单例,只需调用变量 class.func,DI 会负责对象的生命周期
  • DI 容器在启动后立即验证所有依赖,并告诉您是否可以构造所有依赖

请参阅这篇简短但信息丰富的文章,了解有关 solid 原则的更多信息:medium.com

安装

LightIoC 通过 CocoaPods 提供。要安装它,只需在 Podfile 中添加以下行即可

pod 'LightIoC'

开发环境搭建

包含涵盖整个框架的测试,例如克隆仓库并运行 pod install。然后您可以运行测试方案 LightIoC-Example

使用方法

1) 定义您服务的协议和模块

// Your protocol
protocol SingletonService {
    var id: String { get }
}

// Your class to be injected
class Singleton: SingletonService {
    let id: String = "singleton id"
}

// All registrations are in modules so you can separate layer/framework specific services
struct DatabaseLayerModule: IoCModule {
    func register(container: IoCContainer) {
        do {
            try container.registerSingleton(SingletonService.self, Singleton())
        } catch {
            // Handle error
        }
    }
}

2) 在应用启动时注册模块,例如在AppDelegate中,但在请求第一个依赖项之前注册

class AppDelegate: UIResponder, UIApplicationDelegate {
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        IoC.register(module: DatabaseLayerModule())

        // IoC.register(module: BusinessLayerModule())
        // etc...

        return true
    }
}

3) 现在您可以注入并访问您的服务

class ViewController: UIViewController {

    @Dependency var singleton: SingletonService

    override func viewDidLoad() {
        super.viewDidLoad()
        
        print(singleton.id)
        // result: "singleton id"
    }
}

覆盖

您可以通过调用 IoC.registerAndOverwrite(module:) 来使用另一个实例/工厂覆盖已注册的服务。假设您正在编写测试,并想要更改数据库服务的实例以使用模拟服务,则在您的测试中注册另一个符合 IoCOverwriteModule 的模块,其中包含注册和覆盖功能

class MockSingleton: SingletonService {
    let id: String = "mock singleton id"
}

struct MockDatabaseLayerModule: IoCOverwriteModule {
    func register(container: IoCContainer) {
        do {
            try container.overwriteSingleton(SingletonService.self, MockSingleton())
        } catch {
            // Handle error
        }
    }
}

IoC.registerAndOverwrite(module: MockDatabaseLayerModule())

线程安全

所有的解析都是线程安全的,内部集合的访问已同步。

需求

>=Swift 5.1

作者

Ondrej Pisin,[email protected]

许可

LightIoC 在 MIT 许可下可用。更多信息请参阅 LICENSE 文件。