Skip to content

Commit

Permalink
Merge pull request #129 from AliSoftware/features/fixed-reusing-relea…
Browse files Browse the repository at this point in the history
…sed-weak-singletons

Fixed reusing instances for weak singletons
  • Loading branch information
ilyapuchka authored Oct 10, 2016
2 parents 99fb4ea + 21673d1 commit bfacca6
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
4 changes: 3 additions & 1 deletion Sources/Dip.swift
Original file line number Diff line number Diff line change
Expand Up @@ -723,7 +723,9 @@ private class ResolvedInstances {
get {
switch scope {
case .singleton, .eagerSingleton: return singletons[key]
case .weakSingleton: return (weakSingletons[key] as? WeakBoxType)?.unboxed ?? weakSingletons[key]
case .weakSingleton:
if let boxed = weakSingletons[key] as? WeakBoxType { return boxed.unboxed }
else { return weakSingletons[key] }
case .shared: return resolvedInstances[key]
case .unique: return nil
}
Expand Down
19 changes: 17 additions & 2 deletions Tests/DipTests/ComponentScopeTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,9 @@ class ComponentScopeTests: XCTestCase {
("testThatItDoesNotReuseInstanceInSharedScopeResolvedForNilTag", testThatItDoesNotReuseInstanceInSharedScopeResolvedForNilTagWhenResolvingForAnotherTag),
("testThatItReusesInstanceInSharedScopeResolvedForNilTag", testThatItReusesInstanceInSharedScopeResolvedForNilTag),
("testThatItReusesResolvedInstanceWhenResolvingOptional", testThatItReusesResolvedInstanceWhenResolvingOptional),
("testThatItHoldsWeakReferenceToWeakSingletonInstance",
testThatItHoldsWeakReferenceToWeakSingletonInstance)
("testThatItHoldsWeakReferenceToWeakSingletonInstance", testThatItHoldsWeakReferenceToWeakSingletonInstance),
("testThatItResolvesWeakSingletonAgainAfterItWasReleased", testThatItResolvesWeakSingletonAgainAfterItWasReleased),
("testThatCollaboratingContainersReuseSingletonsResolvedByAnotherContainer", testThatCollaboratingContainersReuseSingletonsResolvedByAnotherContainer)
]
}()

Expand Down Expand Up @@ -335,6 +336,20 @@ class ComponentScopeTests: XCTestCase {
XCTAssertNil(weakSingleton)
}

func testThatItResolvesWeakSingletonAgainAfterItWasReleased() {
Dip.logLevel = .Verbose
//given
let service = container.register(.weakSingleton) { ServiceImp1() }
container.register(service, type: Service.self)

//when
//resolve and realease reight away
_ = try? container.resolve() as ServiceImp1

//then
AssertNoThrow(expression: try container.resolve() as Service, "Weak singleton should be resolved again.")
}

func testThatCollaboratingContainersReuseSingletonsResolvedByAnotherContainer() {
func test(_ scope: ComponentScope, line: UInt = #line) {
let container1 = DependencyContainer()
Expand Down

0 comments on commit bfacca6

Please sign in to comment.