Skip to content

Instantly share code, notes, and snippets.

@hannessolo
Created May 1, 2020 17:44
Show Gist options
  • Save hannessolo/984a2e6244226906dbaf49102b35b041 to your computer and use it in GitHub Desktop.
Save hannessolo/984a2e6244226906dbaf49102b35b041 to your computer and use it in GitHub Desktop.
struct DependencyInjector {
private static var dependencyList: [String:Any] = [:]
static func resolve<T>() -> T {
guard let t = dependencyList[String(describing: T.self)] as? T else {
fatalError("No povider registered for type \(T.self)")
}
return t
}
static func register<T>(dependency: T) {
dependencyList[String(describing: T.self)] = dependency
}
}
@propertyWrapper struct Inject<T> {
var wrappedValue: T
init() {
self.wrappedValue = DependencyInjector.resolve()
}
}
@propertyWrapper struct Provider<T> {
var wrappedValue: T
init(wrappedValue: T) {
self.wrappedValue = wrappedValue
DependencyInjector.register(dependency: wrappedValue)
}
}
struct DependencyProvider {
@Provider var fooService: FooService = Foo("Hello") as FooService
}
protocol FooService {
func printMessage()
}
class Foo: FooService {
private let message: String
init(_ message: String) {
self.message = message
}
func printMessage() {
print(message)
}
}
class Bar {
@Inject var foo: FooService
func useFoo() {
foo.printMessage()
}
}
DependencyProvider()
let bar = Bar()
bar.useFoo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment