Add dependency injection
This commit is contained in:
parent
151ed6d78b
commit
bf94769573
9 changed files with 140 additions and 51 deletions
47
ios/Native/Utils/DI/DependencyContainer.swift
Normal file
47
ios/Native/Utils/DI/DependencyContainer.swift
Normal file
|
@ -0,0 +1,47 @@
|
|||
//
|
||||
// DependencyContainer.swift
|
||||
// Vitaway
|
||||
//
|
||||
// Created by Artur Gurgul on 20/06/2025.
|
||||
//
|
||||
|
||||
final class DependencyContainer: Resolver {
|
||||
private var factories: [String: (Resolver) -> Any] = [:]
|
||||
private var instances: [String: Any] = [:]
|
||||
|
||||
func register<T>(_ type: T.Type, cache: Bool = true, factory: @escaping (Resolver) -> T) {
|
||||
let key = String(describing: type)
|
||||
factories[key] = factory
|
||||
|
||||
if cache {
|
||||
instances[key] = factory(self)
|
||||
}
|
||||
}
|
||||
|
||||
func registerSingleton<T>(_ type: T.Type, factory: @escaping (Resolver) -> T) {
|
||||
let key = String(describing: type)
|
||||
factories[key] = factory
|
||||
}
|
||||
|
||||
func resolve<T>() -> T {
|
||||
resolve(type: T.self)
|
||||
}
|
||||
|
||||
func resolve<T>(type: T.Type) -> T {
|
||||
let key = String(describing: T.self)
|
||||
|
||||
if let instance = instances[key] as? T {
|
||||
return instance
|
||||
}
|
||||
|
||||
guard let factory = factories[key], let instance = factory(self) as? T else {
|
||||
fatalError("No registered entry for type \(key)")
|
||||
}
|
||||
return instance
|
||||
}
|
||||
|
||||
static var shared: DependencyContainer {
|
||||
(UIApplication.shared.delegate as! AppDelegate).sharedState.container
|
||||
}
|
||||
}
|
||||
|
16
ios/Native/Utils/DI/Injected.swift
Normal file
16
ios/Native/Utils/DI/Injected.swift
Normal file
|
@ -0,0 +1,16 @@
|
|||
//
|
||||
// Injected.swift
|
||||
// Vitaway
|
||||
//
|
||||
// Created by Artur Gurgul on 05/07/2025.
|
||||
//
|
||||
|
||||
import UIKit
|
||||
|
||||
@propertyWrapper
|
||||
class Injected<T> {
|
||||
var wrappedValue: T {
|
||||
DependencyContainer.shared.resolve(type: T.self)
|
||||
}
|
||||
|
||||
}
|
10
ios/Native/Utils/DI/Resolver.swift
Normal file
10
ios/Native/Utils/DI/Resolver.swift
Normal file
|
@ -0,0 +1,10 @@
|
|||
//
|
||||
// Resolver.swift
|
||||
// Vitaway
|
||||
//
|
||||
// Created by Artur Gurgul on 20/06/2025.
|
||||
//
|
||||
|
||||
protocol Resolver {
|
||||
func resolve<T>() -> T
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue