Needle 是一个用于 Swift 的依赖注入 (DI) 系统。与其他 DI 框架(如 Cleanse、Swinject)不同,Needle 提倡分层 DI 结构,并利用代码生成来确保编译时安全。这使我们能够充满信心地开发应用程序和进行代码更改。如果它能编译通过,就能正常工作。 在这方面,Needle 更类似于 JVM 的 Dagger。
Needle 旨在实现以下主要目标
使用 Needle 为您的应用程序编写 DI 代码既简单又编译时安全。每个依赖范围都由一个 Component
定义。并且它的依赖项封装在一个 Swift protocol
中。两者使用 Swift 泛型链接在一起。
/// This protocol encapsulates the dependencies acquired from ancestor scopes.
protocol MyDependency: Dependency {
/// These are objects obtained from ancestor scopes, not newly introduced at this scope.
var chocolate: Food { get }
var milk: Food { get }
}
/// This class defines a new dependency scope that can acquire dependencies from ancestor scopes
/// via its dependency protocol, provide new objects on the DI graph by declaring properties,
/// and instantiate child scopes.
class MyComponent: Component<MyDependency> {
/// A new object, hotChocolate, is added to the dependency graph. Child scope(s) can then
/// acquire this via their dependency protocol(s).
var hotChocolate: Drink {
return HotChocolate(dependency.chocolate, dependency.milk)
}
/// A child scope is always instantiated by its parent(s) scope(s).
var myChildComponent: MyChildComponent {
return MyChildComponent(parent: self)
}
}
使用 Needle 编写 DI 代码时,基本上就是这样。正如您所看到的,一切都是真实的、可编译的 Swift 代码。没有脆弱的注释或“注解”。快速回顾一下,这里的三个关键概念是依赖协议、组件和子组件的实例化。有关更详细的解释和高级主题,请参阅下面的“Needle 入门”部分。
使用和集成 Needle 分为两个步骤。以下每个步骤在链接的文档中都有详细的说明和解释。
Needle 有两个部分:NeedleFoundation
框架和可执行代码生成器。为了使用 Needle 作为您的 DI 系统,这两个部分都需要与您的 Swift 项目集成。
请按照标准的 Carthage 安装流程将 NeedleFoundation
框架与您的 Swift 项目集成。
github "https://github.com/uber/needle.git" ~> VERSION_OF_NEEDLE
请通过标准的 Swift Package Manager 包定义流程将 Needle 指定为依赖项,以将 NeedleFoundation
框架与您的 Swift 项目集成。
dependencies: [
.package(url: "https://github.com/uber/needle.git", .upToNextMajor(from: "VERSION_NUMBER")),
],
targets: [
.target(
name: "YOUR_MODULE",
dependencies: [
"NeedleFoundation",
]),
],
请按照标准的 pod 集成流程并使用 NeedleFoundation
pod。
如果使用 Carthage 集成 NeedleFoundation
框架,则相应版本的代码生成器可执行文件的副本已下载到 Carthage 文件夹中。它可以在 Carthage/Checkouts/needle/Generator/bin/needle
找到。
无论 NeedleFoundation
框架如何集成到您的项目中,生成器始终可以通过 Homebrew 安装。
brew install needle
链接的文档使用了一个相对真实的示例来解释什么是依赖注入模式及其好处。
如果您喜欢 Needle,请查看我们团队的其他相关开源项目