hmlongco / Factory

A new approach to Container-Based Dependency Injection for Swift and SwiftUI.
MIT License
1.7k stars 107 forks source link

Using Factory in a Sendable conforming Class #168

Closed sebanitu closed 3 months ago

sebanitu commented 7 months ago

Hi! First of wall a huge thank you for all of the hard work you've put into Factory, I love it! I was wondering if there is any way in which @Injected properties can be used within a Sendable conforming Class while also avoiding the Concurrency warning related to mutability.

Example:

final class Service: Sendable {
    @Injected(\.apiClient) private var apiClient
    ....
}

-> throws a warning "stored property '_apiClient' of 'Sendable'-conforming class 'Service' is mutable"

Thanks you in advance for looking at this!

hmlongco commented 7 months ago

There doesn't appear to be an easy way to fix @Injected at the moment.

As such, your two options appear to be..

1) Marking the class as @MainActor. Which may or may not cause MainActor cascades.

@MainActor
final class Service: Sendable {
    @Injected(\.apiClient) private var apiClient
    ....
}

2) Wrapping the value in a lock.

let apiClient = OSAllocatedUnfairLock(uncheckedState: Container.shared.apiClient)

May have to look into an @InjectSendable wrapper....