Skip to content

Instantly share code, notes, and snippets.

@TheWorstProgrammerEver
Created February 6, 2022 10:16
Show Gist options
  • Save TheWorstProgrammerEver/07c51b63fc765e54c5d94e9dbf299d33 to your computer and use it in GitHub Desktop.
Save TheWorstProgrammerEver/07c51b63fc765e54c5d94e9dbf299d33 to your computer and use it in GitHub Desktop.
Swift Service Locator / IoC Container / Dependency Registry & Resolver (haha gross)
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