Created
February 6, 2022 10:16
-
-
Save TheWorstProgrammerEver/07c51b63fc765e54c5d94e9dbf299d33 to your computer and use it in GitHub Desktop.
Swift Service Locator / IoC Container / Dependency Registry & Resolver (haha gross)
This file contains hidden or 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
class Container : DependencyRegistry, DependencyResolver { | |
private var registrations: [String : () -> Any] = [:] | |
func register<T>(_ t: T.Type, _ f: @escaping @autoclosure () -> T) { | |
registrations[key(for: t)] = f | |
} | |
func resolve<T>() -> T { | |
registrations[key(for: T.self)]!() as! T | |
} | |
private func key(for type: Any.Type) -> String { | |
.init(describing: type) | |
} | |
} | |
protocol DependencyRegistry { | |
func register<T>(_ t: T.Type, _ f: @escaping () -> T) | |
} | |
protocol DependencyResolver { | |
func resolve<T>() -> T | |
} | |
extension DependencyResolver { | |
func configure(_ c: (Self) -> Void) -> Self { | |
c(self) | |
return self | |
} | |
} | |
let container: Container = .init() | |
.configure { c in | |
c.register(Interface.self, Implementation.init) | |
c.register(OtherInterface.self, HasThreeDependencies(c.resolve, c.resolve, c.resolve)) // Haha yucky gross stinky | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment