Added DependencyInjector as simple dependency injection framework

This commit is contained in:
dankito 2020-07-15 22:48:29 +02:00
parent 5734fd38f0
commit 322910496f
1 changed files with 25 additions and 0 deletions

View File

@ -0,0 +1,25 @@
/**
Code copied from Hannes Hertach, https://medium.com/@hanneshertach/swiftui-dependency-injection-in-20-lines-b322457065a5
*/
struct DependencyInjector {
private static var dependencyList: [String:Any] = [:]
static func resolve<T>() -> T {
guard let t = dependencyList[String(describing: T.self)] as? T else {
fatalError("No povider registered for type \(T.self)")
}
return t
}
static func register<T>(dependency: T) {
dependencyList[String(describing: T.self)] = dependency
}
}
@propertyWrapper struct Inject<T> {
var wrappedValue: T
init() {
self.wrappedValue = DependencyInjector.resolve()
}
}