一个极简的类型安全 Swift 依赖注入工厂。所有真正的实例都在这里铸造。
循环引用仅通过使用 setter 注入来处理。这是因为所有实例都在构造阶段创建,然后才触发 setter 注入,从而允许在需要它们之前引用存在。
你可以将源代码复制到你的项目中,或者设置此 repo 的 git 子模块并将项目作为子项目拖到你的项目中。
import FieryCrucible
import UIKit
class CustomFactory : DependencyFactory {
func application() -> CustomApplication {
return shared(CustomApplication()) { instance in
instance.factory = self
}
}
func mainWindow() -> UIWindow {
return shared(
factory: {
let instance = UIWindow(frame: UIScreen.mainScreen().bounds)
instance.backgroundColor = UIColor.whiteColor()
return instance
},
configure: { instance in
instance.rootViewController = self.rootViewController()
}
)
}
func rootViewController() -> UIViewController {
return scoped(UITabBarController()) { instance in
instance.viewControllers = [
self.tab0ViewController(),
self.tab1ViewController(),
]
}
}
...
}
class CustomApplication {
var factory: CustomFactory!
func launch() {
factory.mainWindow().makeKeyAndVisible()
}
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var factory: CustomFactory!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
factory = CustomFactory()
factory.application().launch()
return true
}
}