Skip to content

Commit

Permalink
Correctly handle forwarded type registrations
Browse files Browse the repository at this point in the history
Forwarded types are commonly created using `.implements()`
  • Loading branch information
bradfol committed Nov 8, 2024
1 parent 85c6f70 commit 5ae0b17
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
3 changes: 2 additions & 1 deletion Sources/Knit/DuplicateDetection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,9 @@ extension DuplicateDetection: Behavior {
toService entry: ServiceEntry<Service>,
withName name: String?
) {
// Make sure to use `didRegisterType type: Type.Type` rather than `Service`
let key = Key(
serviceType: Service.self,
serviceType: type,
argumentsType: entry.argumentsType,
name: name
)
Expand Down
18 changes: 18 additions & 0 deletions Tests/KnitTests/DuplicateDetectionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,24 @@ final class DuplicateDetectionTests: XCTestCase {
XCTAssertEqual(reportedDuplicates.count, 0)
}

func testTypeForwarding() throws {
// A forwarded type (`.implements()`) should not cause a duplicate registration
let duplicateDetection = DuplicateDetection()
let container = Container(behaviors: [duplicateDetection])

XCTAssertEqual(duplicateDetection.detectedKeys.count, 0)
container.register(String.self, factory: { _ in "string"} )
.implements((any StringProtocol).self)
XCTAssertEqual(duplicateDetection.detectedKeys.count, 0)

// Registering `Substring` does not cause a duplicate
let substringEntry = container.register(Substring.self, factory: { _ in "substring"} )
XCTAssertEqual(duplicateDetection.detectedKeys.count, 0)
// However forwarding to the same type twice still results in a duplicate
substringEntry.implements((any StringProtocol).self)
XCTAssertEqual(duplicateDetection.detectedKeys.count, 1)
}

func testCustomStringDescription() throws {
assertCustomStringDescription(key: DuplicateDetection.Key(
serviceType: String.self,
Expand Down

0 comments on commit 5ae0b17

Please sign in to comment.