ViperServices
介绍
ViperServices是用Swift编写的iOS应用程序的依赖注入容器。它在使用方面比Kraken、Guise等更轻量级和简单。
它还引入了服务的“可引导”概念。此外,服务可以定义它们所依赖的单元。
变更日志
请参阅 变更日志
安装
Cocoapods
这是推荐安装此包的方式。
- 将以下行添加到您的 Podfile 中
pod 'ViperServices'
- 运行以下命令以获取并构建您的依赖项
pod install
手动安装
如果您想手动安装此包,请按照以下步骤操作
- 确保您的项目是一个 git 仓库。如果不是,只需从您的项目根目录运行此命令
git init
- 通过运行以下命令将 ViperServices 添加为 git 子模块。
git submodules add https://github.com/ladeiko/ViperServices.git
- 将 'submodules/ViperServices/Sources' 文件夹中的文件添加到您的项目中。
使用方法
- 定义您的 viper 服务
import ViperServices
protocol Service1: AnyObject {
func foo()
}
class Service1Impl: Service1, ViperService {
func setupDependencies(_ container: ViperServicesContainer) -> [AnyObject]? {
return [ // depends on
container.resolve() as Service2
]
}
func boot(launchOptions: [UIApplication.LaunchOptionsKey : Any]?, completion: @escaping ViperServiceBootCompletion) {
print("boot 1 called")
completion(.succeeded) // sync completion
}
func foo() {
print("foo 1 called")
}
}
protocol Service2: AnyObject {
func foo()
}
enum Service2Error: Error {
case SomeError
}
class Service2Impl: Service2, ViperService {
private weak var container: ViperServicesContainer!
func setupDependencies(_ container: ViperServicesContainer) -> [AnyObject]? {
self.container = container
return nil
}
func boot(launchOptions: [UIApplication.LaunchOptionsKey : Any]?, completion: @escaping ViperServiceBootCompletion) {
print("boot 2 called")
DispatchQueue.main.asyncAfter(deadline: .now() + 3) { // async completion
switch arc4random() % 2 { // emulate random result
case 0:
completion(.failed(error: Service2Error.SomeError))
default:
completion(.succeeded)
}
}
}
func foo() {
print("foo 2 called")
}
}
- 将以下代码添加到应用程序代理中
var window: UIWindow?
// use DefaultViperServicesContainer or implement your own container
let services = DefaultViperServicesContainer()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
try! services.register(Service1Impl() as Service1)
try! services.register(Service2Impl() as Service2)
services.boot(launchOptions: launchOptions) { (result) in
switch result {
case .succeeded:
// All ok, now it is safe to use any service!
(self.services.resolve() as Service1).foo()
(self.services.resolve() as Service2).foo()
case let .failed(failedServices):
// Boot failed, show error to user
let alert = UIAlertController(title: "Error",
message: failedServices.first!.error.localizedDescription,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.window!.rootViewController?.present(alert, animated: false, completion: nil)
}
}
return true
}
许可协议
本项目采用MIT许可协议 - 请参阅LICENSE文件了解详细信息