Skip to content

Commit ca24cb7

Browse files
committed
fix: Support Structs and Protocols as Weak Objects
1 parent 86ae879 commit ca24cb7

File tree

4 files changed

+18
-4
lines changed

4 files changed

+18
-4
lines changed

Sources/AstrojectCore/Instances/Weak.swift

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,14 @@ import Foundation
1212
/// The `Weak` class implements the `Instance` protocol and represents a weak reference scope for dependency injection.
1313
/// It holds a weak reference to the product instance, allowing it to be deallocated when
1414
/// no longer strongly referenced elsewhere.
15-
class Weak<Product: AnyObject>: Instance {
15+
class Weak<Product>: Instance {
1616
/// The weak reference to the product instance.
17-
weak var product: Product?
17+
weak var object: AnyObject?
18+
19+
var product: Product? {
20+
get { object as? Product }
21+
set { object = newValue as AnyObject }
22+
}
1823

1924
/// Initializes a new `Weak` instance.
2025
init() {}

Sources/AstrojectCore/Registration/Registrable.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ public extension Registrable {
9090
///
9191
/// - Returns: The modified `Registration` instance.
9292
@discardableResult
93-
func asWeak() -> Self where Product: AnyObject {
93+
func asWeak() -> Self {
9494
return self.as(Weak())
9595
}
9696

Tests/CoreTests/ContainerTests.swift

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -966,7 +966,6 @@ extension ContainerTests {
966966

967967
#expect(object3Count == 10)
968968
}
969-
970969
}
971970
}
972971

Tests/CoreTests/InstanceTests.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,16 @@ struct InstanceTests {
8585
dog = nil
8686
#expect(instance.get(for: context) == nil)
8787
}
88+
89+
@Test("Instance can hold structs")
90+
func weakStruct() {
91+
let instance = Weak<StructAnimal>()
92+
let context = Context.fresh()
93+
let animal = StructAnimal()
94+
instance.set(animal, for: context)
95+
instance.release(for: context)
96+
#expect(instance.get(for: context) == nil)
97+
}
8898
}
8999

90100
@Suite("Graph")

0 commit comments

Comments
 (0)