Skip to content

Commit 83f1a82

Browse files
committed
Resolution reporting to Behavior
1 parent 61849dd commit 83f1a82

2 files changed

Lines changed: 39 additions & 1 deletion

File tree

Sources/Swinject/Behavior.swift

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,11 @@
44

55
/// Protocol for adding functionality to the container
66
public protocol Behavior {
7+
/// Whether the container should report resolutions to this Behavior.
8+
/// If `true`, `container(_:didResolve:name:)` will be called after each successful resolution.
9+
/// Defaults to `false`.
10+
var shouldReportResolution: Bool { get }
11+
712
/// This will be invoked on each behavior added to the `container` for each `entry` added to the container using
813
/// one of the `register()` or type forwarding methods
914
///
@@ -21,4 +26,31 @@ public protocol Behavior {
2126
toService entry: ServiceEntry<Service>,
2227
withName name: String?
2328
)
29+
30+
/// This will be invoked after a successful resolution if `shouldReportResolution` is `true`.
31+
///
32+
/// - Parameters:
33+
/// - container: container from which the service was resolved
34+
/// - serviceType: The type that was resolved
35+
/// - name: The registration name used for resolution (if any)
36+
/// - duration: The time taken to resolve the service
37+
func container<Service>(
38+
_ container: SwinjectContainer,
39+
didResolve serviceType: Service.Type,
40+
name: String?,
41+
duration: Duration
42+
)
43+
}
44+
45+
// MARK: - Default Implementations
46+
47+
public extension Behavior {
48+
var shouldReportResolution: Bool { false }
49+
50+
func container<Service>(
51+
_ container: SwinjectContainer,
52+
didResolve serviceType: Service.Type,
53+
name: String?,
54+
duration: Duration
55+
) {}
2456
}

Sources/Swinject/SwinjectContainer.swift

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,8 @@ extension SwinjectContainer: _Resolver {
227227
) -> Service? {
228228
// No need to use weak self since the resolution will be executed before
229229
// this function exits.
230-
sync {
230+
let start = ContinuousClock.now
231+
return sync {
231232
var resolvedInstance: Service?
232233
let key = ServiceKey(serviceType: Service.self, argumentsType: Arguments.self, name: name, option: option)
233234

@@ -249,6 +250,11 @@ extension SwinjectContainer: _Resolver {
249250
key: key,
250251
availableRegistrations: getRegistrations()
251252
)
253+
} else {
254+
let duration = ContinuousClock.now - start
255+
behaviors
256+
.filter { $0.shouldReportResolution }
257+
.forEach { $0.container(self, didResolve: Service.self, name: name, duration: duration) }
252258
}
253259

254260
return resolvedInstance

0 commit comments

Comments
 (0)