TestsTested | ✓ |
LangLanguage | SwiftSwift |
License | MIT |
ReleasedLast Release | Mar 2015 |
SPMSupports SPM | ✗ |
Maintained by Vadym Markov.
A simple Swift implementation of Service Locator / IOC container with limited DI functionality. Works well with Swift and Objective C classes.
@objc
annotation.NSObject
to let the container automatically resolve dependencies.import Kontena
let container = Container() // init
let sharedContainer = Container.sharedInstance // as singleton
// all bound objects from container2
// are merged and added to container1
container1.mergeWithContainer(container2)
container.clear()
container.resolveDependencies = true
@objc protocol SomeProtocol {}
class SomeBaseClass: NSObject {}
class SomeClass: SomeBaseClass, SomeProtocol {}
var instance = SomeClass()
// as singleton to the type of the instance
container.bind(instance)
// as singleton to the superclass type
container.bind(instance, toType: SomeBaseClass.self)
// as singleton to the protocol
container.bind(instance, toType: SomeProtocol.self)
// as singleton to the key
container.bind(instance, toKey: "some")
// factory = closure where the object is initialized
let factory = {
() -> SomeClass in
let some = SomeClass()
// basic initialization
return some
}
// to the type of the instance
container.bindFactory(factory)
// to the type of the instance
container.bindFactory(factory, toType: SomeBaseClass.self)
// to the protocol
container.bindFactory(factory, toType: SomeProtocol.self)
// to the key
container.bindFactory(factory, toKey: "some")
// you can bind factory as singleton as well
container.bindFactory(factory).asSingleton()
Resolved object or nil
is returned. If the factory was bound then object will be initialized lazily (for factories with the singleton
scope - only at the first resolve call, for the prototype
scope - at every resolve call).
If resolveDependencies
was set to true
then container will try to automatically resolve dependencies of the requested object (if they are already registered in the container and the requested object is a subclass of NSObject
).
var resolvedByType = container.resolveType(SomeClass.self)
var resolvedByKey = container.resolveKey(key)
var instance = SomeClass()
var resolvedInstance: SomeClass?
// should be bound to the shared container
Container.sharedInstance.bind(instance)
// Resolve and inject from the container
-->resolvedInstance // prefix operator
resolvedInstance<-- // postfix operator
Kontena is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'Kontena'
Vadym Markov, [email protected]
Kontena is available under the MIT license. See the LICENSE file for more info.