Last active
July 14, 2021 18:54
-
-
Save kvs-coder/17ff8453fd8290490121ba5de1d32851 to your computer and use it in GitHub Desktop.
Dependency injector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
@propertyWrapper | |
struct Injection<T> { | |
var wrappedValue: T | |
init() { | |
self.wrappedValue = DependencyContainer.getDependency() | |
} | |
} | |
final class DependencyContainer { | |
private static var dependencies = [ObjectIdentifier: Any]() | |
static func register<T>(_ dependency: T.Type, instance: T) { | |
let key = ObjectIdentifier(dependency) | |
dependencies[key] = instance as Any | |
} | |
static func getDependency<T>() -> T { | |
let key = ObjectIdentifier(T.self) | |
guard let dependency = dependencies[key] as? T else { | |
fatalError("No dependency found for \(key)-\(T.self)!") | |
} | |
return dependency | |
} | |
static func remove<T>(_ dependency: T.Type) { | |
let key = ObjectIdentifier(dependency) | |
dependencies.removeValue(forKey: key) | |
} | |
static func clear() { | |
dependencies.removeAll() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment