Skip to content

Instantly share code, notes, and snippets.

@xxKRASHxx
Last active November 20, 2017 13:23
Show Gist options
  • Save xxKRASHxx/5b8019ba50f211b1b626b2f4ebb68158 to your computer and use it in GitHub Desktop.
Save xxKRASHxx/5b8019ba50f211b1b626b2f4ebb68158 to your computer and use it in GitHub Desktop.
SwiftInject DI Example
class AnyInteractor: DBAccessable {
/*
easy access to self.dbService
*/
}
class AppDelegate {
//...
fileprivate let container = Container.defaultContainer() { container in
container.register(DBServiceProtocol.self) { _ in CoreDataService() } .inObjectScope(.container)
}
//...
}
class CoreDataService: DBServiceProtocol {
/*
protocol implementation
*/
}
protocol DBServiceProtocol {
func eat()
func pray()
func love()
}
protocol DBAccessable {
var dbService : DBServiceProtocol { get }
}
extension DBAccessable {
var dbService : DBServiceProtocol { get { return Container.defaultContainer().resolve(DBServiceProtocol.self)! } }
}
import Foundation
import Swinject
fileprivate static let _defaultContainer = Container()
extension Container {
public static func defaultContainer() -> Container { return _defaultContainer }
public static func defaultContainer( _ registeringClosure: (Container) -> Void) -> Container {
registeringClosure(_defaultContainer)
return _defaultContainer
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment