DIKit
DIKit copied to clipboard
Add Shared<T> to return shared instance in provider method
Rough sketch:
final class Counter {
var value = 0
}
protocol MyResolver: Resolver {
// A MyResolver instance always returns the same instance of Counter.
func provideCounter() -> Shared<Counter>
}
// Generated code
extension MyResolver {
func resolveCounter() -> Counter {
final class Scope {
// NOTE: WeakDictionary doesn't present in standard library.
static var sharedInstances = [:] as WeakDictionary<MyResolver, Counter>
}
// Return shared instance associated with MyResolver instance if it presents.
if let sharedInstance = Scope.sharedInstances[self] {
return associatedObject
}
// If shared instance is not found, call provider method and save returned instance as a shared instance.
let sharedInstance = provideCounter()
Scope.sharedInstances[self] = sharedInstance
return sharedInstance
}
}