Needle 是 Uber 开发的一个 Swift 的依赖注入框架。和其他 DI 框架(如 Cleanse, Swinject ) 不同的是,Needle 鼓励层次化的 DI 结构以及利用代码生成器来确保编译时安全。这样我们在修改应用代码的时候可以更有信心,如果能编译通过就表示其执行就会正常。Needle 更像是 Dagger for the JVM.
Needle 主要实现以下目标:
示例代码
/// 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) } }