Uber NeedleSwift 的依赖注入框架

联合创作 · 2023-09-30 06:56

Needle 是 Uber 开发的一个 Swift 的依赖注入框架。和其他 DI 框架(如 CleanseSwinject ) 不同的是,Needle 鼓励层次化的 DI 结构以及利用代码生成器来确保编译时安全。这样我们在修改应用代码的时候可以更有信心,如果能编译通过就表示其执行就会正常。Needle 更像是 Dagger for the JVM.

Needle 主要实现以下目标:

  1. 通过确保依赖注入代码的编译时安全来提供可靠性
  2. 确保代码生成是高性能的
  3. 兼容所有 iOS 应用架构,包括 RIBs, MVx 等.

示例代码

/// 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)
    }
}
浏览 8
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报