JSInject
这是使用 Swift 5.1
的 @propertyWrapper
功能构建的 Swift
DI (依赖注入) 容器。
安装
CocoaPods
pod 'JSInject'
用法
注册
您可以使用 Container
进行注册。我认为,在 AppDelegate
中注册对象是合适的位置。
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Register services into container
Container.shared.register(Animal.self) { Animal("Steve") }
...
}
}
支持如使用名称的多容器或多依赖等选项。
public class Container {
public func register<Value: AnyObject>(
_ type: Value.Type,
scope: Scope = .global,
name: String? = nil,
container: String = Name.default,
factory: @escaping () -> Value
)
...
}
注入
可以使用@Inject
属性包装器进行注入。
class AnyClass {
@Inject()
var animal: Animal
@Inject(name: "stub")
var animal: Animal
@Inject(name: "stub", container: "test")
var animal: Animal
}
如果您想要在实例化对象时决定依赖注入的类型,请使用setName()
或setContainer()
。
class AnyClass {
@Inject()
var animal: Animal
init(isTest: Bool) {
if isTest {
// Get origin property wrapper object using '_' prefix.
_animal.setName("test")
}
}
}
完成!
作用域
JSInject
服务支持三种对象存活的作用域。
public enum Scope {
case global
case retain
case property
}
.global
对象在应用程序运行期间一直存活。.retain
对象通过保留周期存活。.property
对象将在每次实例化时创建。
如果您想了解它是如何工作的,请查看示例应用程序。
参考
我受到了这篇文章的启发。
贡献
这是一个关于DI的想法。所以欢迎任何想法、问题、意见。
许可
JSInject
可在MIT许可下使用。