diff --git a/CHANGELOG b/CHANGELOG index 9555f0ec..52f93a34 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,9 @@ # Factory Changelog +### 1.0.3 + +* Streamline handling of optionals in registered + ### 1.0.2 * Refactored common scope cache mechanism diff --git a/Sources/Factory/Factory.swift b/Sources/Factory/Factory.swift index ef9c9972..c44c1cdf 100644 --- a/Sources/Factory/Factory.swift +++ b/Sources/Factory/Factory.swift @@ -125,11 +125,10 @@ open class SharedContainer { defer { lock.unlock() } lock.lock() if let registration = registrations[id] { - let result = registration() - if let optional = result as? T? { + if _isOptional(T.self), let optional = registration() as? T? { return optional } - return result as? T + return registration() as? T } return nil } diff --git a/Tests/FactoryTests/FactoryRegistrationTests.swift b/Tests/FactoryTests/FactoryRegistrationTests.swift index 31bf7cd8..f5b16b10 100644 --- a/Tests/FactoryTests/FactoryRegistrationTests.swift +++ b/Tests/FactoryTests/FactoryRegistrationTests.swift @@ -14,16 +14,26 @@ final class FactoryRegistrationTests: XCTestCase { let service1 = Container.myServiceType() XCTAssertTrue(service1.text() == "MyService") - Container.Registrations.push() - - Container.myServiceType.register(factory: { MockService() }) + // add registrtion and test initial state + Container.myServiceType.register(factory: { MockServiceN(1) }) let service2 = Container.myServiceType() - XCTAssertTrue(service2.text() == "MockService") + XCTAssertTrue(service2.text() == "MockService1") + + // push and test changed state + Container.Registrations.push() + Container.myServiceType.register(factory: { MockServiceN(2) }) + let service3 = Container.myServiceType() + XCTAssertTrue(service3.text() == "MockService2") + // pop and ensure we're back to initial state Container.Registrations.pop() + let service4 = Container.myServiceType() + XCTAssertTrue(service4.text() == "MockService1") - let service3 = Container.myServiceType() - XCTAssertTrue(service3.text() == "MyService") + // pop again (which does nothing) and test for initial state + Container.Registrations.pop() + let service5 = Container.myServiceType() + XCTAssertTrue(service5.text() == "MockService1") } func testReset() throws { diff --git a/Tests/FactoryTests/MockServices.swift b/Tests/FactoryTests/MockServices.swift index 75c7efd4..4d8633ff 100644 --- a/Tests/FactoryTests/MockServices.swift +++ b/Tests/FactoryTests/MockServices.swift @@ -27,6 +27,17 @@ class MockService: MyServiceType { } } +class MockServiceN: MyServiceType { + let id = UUID() + let n: Int + init(_ n: Int) { + self.n = n + } + func text() -> String { + "MockService\(n)" + } +} + struct ValueService: MyServiceType { let id = UUID() func text() -> String {