hmlongco / Factory

A new approach to Container-Based Dependency Injection for Swift and SwiftUI.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Using Factory in a Sendable conforming Class

sebanitu opened this issue · comments

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!

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
    ....
}
  1. Wrapping the value in a lock.
let apiClient = OSAllocatedUnfairLock(uncheckedState: Container.shared.apiClient)

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