To run the example project, clone the repo, and run pod install
from the Example directory first.
- Swift 4.0
EasyDependency is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'EasyDependency', '~> 1.0'
EasyDependency is a very lightweight dependency injection framework, without magic. Just a container to register and resolve dependencies. There is no focus on adding support for circular dependencies or automatic injection of dependencies. Simplicity is key.
- Register & retrieve dependencies from a DI container.
- Resolve list of implementations.
- Register dependencies as singletons.
import EasyDependency
class AppContainer: Container {
var superContainer: Container?
var registrations: [Any] = []
required init(container: Container? = nil) {
self.superContainer = container
}
}
This way you register an implementation on a protocol.
let appContainer = AppContainer()
appContainer.register(Storage.self) { _ in StorageAImpl() }
appContainer.register(Storage.self) { _ in StorageBImpl() }
appContainer.register(Storage.self, .singleton) { _ in StorageBImpl() }
You can retrieve the implementation by resolve the dependency by its interface.
let storageImplementation: Storage? = try? appContainer.resolve()
let storageList: [Storage] = appContainer.resolveList()
You can create feature containers including the super container. Registrations on the feature container are used in favor of the super container.
let appContainer = AppContainer()
appContainer.register(Storage.self) { _ in StorageAImpl() }
appContainer.register(String.self) { _ in "StringExample" }
let featureContainer = FeatureContainer(container: appContainer)
featureContainer.register(Storage.self) { container in StorageBImpl(string: try container.resolve()) }
let storageImplementation: Storage? = try? featureContainer.resolve() // StorageBImpl() will be returned.
This concept is created together with Jelle Heemskerk (Github).
NielsKoole (Twitter)
EasyDependency is available under the MIT license. See the LICENSE file for more info.