Dependency Injection Framework for Swift, inspired by KOIN. Basically an implementation of service-locator pattern, living within the application's context (through the AppDelegate
).
Grow as you go!
We started small, it perfectly fits our use case.
DIKit can be installed using Carthage. After installing Carthage just add DIKit to your Cartfile:
github "benjohnde/DIKit" ~> 1.1
CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects. After installing CocoaPods add DIKit to your Podfile:
platform :ios, '9.0'
pod 'DIKit', '~> 1.1.0'
- Define a sub
DependencyContainer
(basically some sort of module declaration):
import DIKit
public extension DependencyContainer {
static var backend = module {
factory { Backend() as BackendProtocol }
}
}
public extension DependencyContainer {
static var network = module {
single { Network() as NetworkProtocol }
}
}
- Let
AppDelegate
adhereDefinesContainer
:
import DIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, DefinesContainer {
let container = modules { .backend; .network }
}
- Inject the dependencies, for instance in a module:
import DIKit
class Backend: BackendProtocol {
@Injectable var network: NetworkProtocol
}
or a ViewController
:
import DIKit
class FirstViewController: UIViewController {
// MARK: - Dependencies
@Injectable var backend: BackendProtocol
// MARK: - View lifecycle
override func viewWillAppear(_ animated: Bool) {
let result = backend.fetch()
print(result)
}
}