You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

42 lines
1.7 KiB

2 years ago
  1. //
  2. // Copyright © 2019 Swinject Contributors. All rights reserved.
  3. //
  4. /// A configuration how an instance provided by a `Container` is shared in the system.
  5. /// The configuration is ignored if it is applied to a value type.
  6. public protocol ObjectScopeProtocol: AnyObject {
  7. /// Used to create `InstanceStorage` to persist an instance for single service.
  8. /// Will be invoked once for each service registered in given scope.
  9. func makeStorage() -> InstanceStorage
  10. }
  11. /// Basic implementation of `ObjectScopeProtocol`.
  12. public class ObjectScope: ObjectScopeProtocol, CustomStringConvertible {
  13. public private(set) var description: String
  14. private var storageFactory: () -> InstanceStorage
  15. private let parent: ObjectScopeProtocol?
  16. /// Instantiates an `ObjectScope` with storage factory and description.
  17. /// - Parameters:
  18. /// - storageFactory: Closure for creating an `InstanceStorage`
  19. /// - description: Description of object scope for `CustomStringConvertible` implementation
  20. /// - parent: If provided, its storage will be composed with the result of `storageFactory`
  21. public init(
  22. storageFactory: @escaping () -> InstanceStorage,
  23. description: String = "",
  24. parent: ObjectScopeProtocol? = nil
  25. ) {
  26. self.storageFactory = storageFactory
  27. self.description = description
  28. self.parent = parent
  29. }
  30. /// Will invoke and return the result of `storageFactory` closure provided during initialisation.
  31. public func makeStorage() -> InstanceStorage {
  32. if let parent = parent {
  33. return CompositeStorage([storageFactory(), parent.makeStorage()])
  34. } else {
  35. return storageFactory()
  36. }
  37. }
  38. }