Add DIContainer singleton with key path registration
This commit is contained in:
parent
cc5c836f04
commit
e829b8141b
1 changed files with 34 additions and 0 deletions
34
Sources/LuminateCore/DIContainer.swift
Normal file
34
Sources/LuminateCore/DIContainer.swift
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import Foundation
|
||||
|
||||
@MainActor
|
||||
public final class DIContainer {
|
||||
|
||||
public static let shared = DIContainer()
|
||||
public private(set) var values = InjectionValues()
|
||||
|
||||
private init() {}
|
||||
|
||||
public func register<T>(
|
||||
_ keyPath: WritableKeyPath<InjectionValues, T?>,
|
||||
value: T
|
||||
) {
|
||||
values[keyPath: keyPath] = value
|
||||
}
|
||||
|
||||
public func resolve<T>(
|
||||
_ keyPath: KeyPath<InjectionValues, T?>
|
||||
) -> T {
|
||||
guard let value = values[keyPath: keyPath] else {
|
||||
fatalError(
|
||||
"DIContainer: No value registered for \(keyPath). "
|
||||
+ "Call DIContainer.shared.register(\\.key, value:) during app startup."
|
||||
)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
public func reset() {
|
||||
values = InjectionValues()
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
Reference in a new issue