一个简单的 Swift 实现,具有有限的功能,用于 Service Locator / IOC 容器和依赖注入功能。它与 Swift 和 Objective-C 类一起工作得很好。
@objc
注释。NSObject
,以便容器能够自动解析依赖关系。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()
返回解析的对象或 nil
。如果工厂已绑定,则在第一次解析调用时,对象会惰性初始化(对于 singleton
作用域,只在第一次解析调用时,对于 prototype
作用域,在每次解析调用时)。
如果设置了 resolveDependencies
为 true
,则容器将尝试自动解析请求对象的依赖关系(如果它们已在容器中注册,并且请求的对象是 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 通过 CocoaPods 提供。要安装它,只需在 Podfile 中添加以下行
pod 'Kontena'
瓦迪姆·马尔科夫,[email protected]
Kontena 在MIT许可证下提供。有关更多信息,请参阅LICENSE文件。