Uber NeedleSwift 的依賴(lài)注入框架
Needle 是 Uber 開(kāi)發(fā)的一個(gè) Swift 的依賴(lài)注入框架。和其他 DI 框架(如 Cleanse, Swinject ) 不同的是,Needle 鼓勵(lì)層次化的 DI 結(jié)構(gòu)以及利用代碼生成器來(lái)確保編譯時(shí)安全。這樣我們?cè)谛薷膽?yīng)用代碼的時(shí)候可以更有信心,如果能編譯通過(guò)就表示其執(zhí)行就會(huì)正常。Needle 更像是 Dagger for the JVM.
Needle 主要實(shí)現(xiàn)以下目標(biāo):
- 通過(guò)確保依賴(lài)注入代碼的編譯時(shí)安全來(lái)提供可靠性
- 確保代碼生成是高性能的
- 兼容所有 iOS 應(yīng)用架構(gòu),包括 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)
}
}評(píng)論
圖片
表情
