|
| 1 | +// |
| 2 | +// AsyncContainer.swift |
| 3 | +// DependencyInjection |
| 4 | +// |
| 5 | +// Created by Róbert Oravec on 17.12.2024. |
| 6 | +// |
| 7 | + |
| 8 | +import Foundation |
| 9 | + |
| 10 | +/// Dependency Injection Container where dependencies are registered and from where they are consequently retrieved (i.e. resolved) |
| 11 | +public actor AsyncContainer: AsyncDependencyResolving, AsyncDependencyRegistering { |
| 12 | + /// Shared singleton |
| 13 | + public static let shared: AsyncContainer = { |
| 14 | + AsyncContainer() |
| 15 | + }() |
| 16 | + |
| 17 | + private var registrations = [RegistrationIdentifier: AsyncRegistration]() |
| 18 | + private var sharedInstances = [RegistrationIdentifier: Any]() |
| 19 | + |
| 20 | + /// Create new instance of ``Container`` |
| 21 | + public init() {} |
| 22 | + |
| 23 | + /// Remove all registrations and already instantiated shared instances from the container |
| 24 | + func clean() { |
| 25 | + registrations.removeAll() |
| 26 | + |
| 27 | + releaseSharedInstances() |
| 28 | + } |
| 29 | + |
| 30 | + /// Remove already instantiated shared instances from the container |
| 31 | + func releaseSharedInstances() { |
| 32 | + sharedInstances.removeAll() |
| 33 | + } |
| 34 | + |
| 35 | + // MARK: Register dependency, Autoregister dependency |
| 36 | + |
| 37 | + |
| 38 | + /// Register a dependency |
| 39 | + /// |
| 40 | + /// - Parameters: |
| 41 | + /// - type: Type of the dependency to register |
| 42 | + /// - scope: Scope of the dependency. If `.new` is used, the `factory` closure is called on each `resolve` call. If `.shared` is used, the `factory` closure is called only the first time, the instance is cached and it is returned for all subsequent `resolve` calls, i.e. it is a singleton |
| 43 | + /// - factory: Closure that is called when the dependency is being resolved |
| 44 | + public func register<Dependency>( |
| 45 | + type: Dependency.Type, |
| 46 | + in scope: DependencyScope, |
| 47 | + factory: @escaping Factory<Dependency> |
| 48 | + ) async { |
| 49 | + let registration = AsyncRegistration(type: type, scope: scope, factory: factory) |
| 50 | + |
| 51 | + registrations[registration.identifier] = registration |
| 52 | + |
| 53 | + // With a new registration we should clean all shared instances |
| 54 | + // because the new registered factory most likely returns different objects and we have no way to tell |
| 55 | + sharedInstances[registration.identifier] = nil |
| 56 | + } |
| 57 | + |
| 58 | + // MARK: Register dependency with argument, Autoregister dependency with argument |
| 59 | + |
| 60 | + /// Register a dependency with an argument |
| 61 | + /// |
| 62 | + /// The argument is typically a parameter in an initiliazer of the dependency that is not registered in the same container, |
| 63 | + /// therefore, it needs to be passed in `resolve` call |
| 64 | + /// |
| 65 | + /// DISCUSSION: This registration method doesn't have any scope parameter for a reason. |
| 66 | + /// The container should always return a new instance for dependencies with arguments as the behaviour for resolving shared instances with arguments is undefined. |
| 67 | + /// Should the argument conform to ``Equatable`` to compare the arguments to tell whether a shared instance with a given argument was already resolved? |
| 68 | + /// Shared instances are typically not dependent on variable input parameters by definition. |
| 69 | + /// If you need to support this usecase, please, keep references to the variable singletons outside of the container. |
| 70 | + /// |
| 71 | + /// - Parameters: |
| 72 | + /// - type: Type of the dependency to register |
| 73 | + /// - factory: Closure that is called when the dependency is being resolved |
| 74 | + public func register<Dependency, Argument>(type: Dependency.Type, factory: @escaping FactoryWithArgument<Dependency, Argument>) async { |
| 75 | + let registration = AsyncRegistration(type: type, scope: .new, factory: factory) |
| 76 | + |
| 77 | + registrations[registration.identifier] = registration |
| 78 | + } |
| 79 | + |
| 80 | + // MARK: Resolve dependency |
| 81 | + |
| 82 | + /// Resolve a dependency that was previously registered with `register` method |
| 83 | + /// |
| 84 | + /// If a dependency of the given type with the given argument wasn't registered before this method call |
| 85 | + /// the method throws ``ResolutionError.dependencyNotRegistered`` |
| 86 | + /// |
| 87 | + /// - Parameters: |
| 88 | + /// - type: Type of the dependency that should be resolved |
| 89 | + /// - argument: Argument that will passed as an input parameter to the factory method that was defined with `register` method |
| 90 | + public func tryResolve<Dependency, Argument>(type: Dependency.Type, argument: Argument) async throws -> Dependency { |
| 91 | + let identifier = RegistrationIdentifier(type: type, argument: Argument.self) |
| 92 | + |
| 93 | + let registration = try getRegistration(with: identifier) |
| 94 | + |
| 95 | + let dependency: Dependency = try await getDependency(from: registration, with: argument) |
| 96 | + |
| 97 | + return dependency |
| 98 | + } |
| 99 | + |
| 100 | + /// Resolve a dependency that was previously registered with `register` method |
| 101 | + /// |
| 102 | + /// If a dependency of the given type wasn't registered before this method call |
| 103 | + /// the method throws ``ResolutionError.dependencyNotRegistered`` |
| 104 | + /// |
| 105 | + /// - Parameters: |
| 106 | + /// - type: Type of the dependency that should be resolved |
| 107 | + public func tryResolve<Dependency>(type: Dependency.Type) async throws -> Dependency { |
| 108 | + let identifier = RegistrationIdentifier(type: type) |
| 109 | + |
| 110 | + let registration = try getRegistration(with: identifier) |
| 111 | + |
| 112 | + let dependency: Dependency = try await getDependency(from: registration) |
| 113 | + |
| 114 | + return dependency |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +// MARK: Private methods |
| 119 | +private extension AsyncContainer { |
| 120 | + func getRegistration(with identifier: RegistrationIdentifier) throws -> AsyncRegistration { |
| 121 | + guard let registration = registrations[identifier] else { |
| 122 | + throw ResolutionError.dependencyNotRegistered( |
| 123 | + message: "Dependency of type \(identifier.description) wasn't registered in container \(self)" |
| 124 | + ) |
| 125 | + } |
| 126 | + |
| 127 | + return registration |
| 128 | + } |
| 129 | + |
| 130 | + func getDependency<Dependency>(from registration: AsyncRegistration, with argument: Any? = nil) async throws -> Dependency { |
| 131 | + switch registration.scope { |
| 132 | + case .shared: |
| 133 | + if let dependency = sharedInstances[registration.identifier] as? Dependency { |
| 134 | + return dependency |
| 135 | + } |
| 136 | + case .new: |
| 137 | + break |
| 138 | + } |
| 139 | + |
| 140 | + // We use force cast here because we are sure that the type-casting always succeed |
| 141 | + // The reason why the `factory` closure returns ``Any`` is that we have to erase the generic type in order to store the registration |
| 142 | + // When the registration is created it can be initialized just with a `factory` that returns the matching type |
| 143 | + let dependency = try await registration.factory(self, argument) as! Dependency |
| 144 | + |
| 145 | + switch registration.scope { |
| 146 | + case .shared: |
| 147 | + sharedInstances[registration.identifier] = dependency |
| 148 | + case .new: |
| 149 | + break |
| 150 | + } |
| 151 | + |
| 152 | + return dependency |
| 153 | + } |
| 154 | +} |
0 commit comments