Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Factory
https://github.com/hmlongco/factory
Admin
A new approach to Container-Based Dependency Injection for Swift and SwiftUI.
Tokens:
50,383
Snippets:
490
Trust Score:
9.5
License:
MIT
Update:
1 month ago
Context
Chat
Benchmark
85.46
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Common setup function returning EmptyView Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Previews.md Shows an alternative setup function that returns EmptyView to be used directly in a #Preview block. ```swift extension Container { func setupMocks() -> EmptyView { myService { MockServiceN(4) } sharedService { MockService2() } return EmptyView() } } #Preview { Container.shared.setupMocks() ContentView() } ``` -------------------------------- ### Common setup function for container Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Previews.md Shows how to add a setup function to a container to register multiple mocks for use in previews or unit tests. ```swift extension Container { func setupMocks() { myService { MockServiceN(4) } sharedService { MockService2() } } } #Preview { let _ = Container.shared.setupMocks() ContentView() } ``` -------------------------------- ### Push and Pop Container State in XCTest setUp/tearDown Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Use Container.shared.manager.push() in setUp and pop() in tearDown to save and restore the registration state, ensuring each test starts from the same initial state. The example also shows registering mock services and testing view model behavior. ```swift final class FactoryCoreTests: XCTestCase { override func setUp() { Container.shared.manager.push() Container.shared.setupMocks() } override func tearDown() { Container.shared.manager.pop() } func testNoAccounts() async { Container.shared.accountLoading { MockNoAccounts() } let model = Container.shared.accountsViewModel() await model.load() XCTAssertTrue(model.isLoaded) XCTAssertTrue(model.isEmpty) } func testError() async { Container.shared.accountLoading { MockAccountError(404) } let model = Container.shared.accountsViewModel() await model.load() XCTAssertTrue(model.isError) } } ``` -------------------------------- ### Trace output example Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Debugging.md Example trace output when tracing is enabled. Each line shows depth, factory, type, and object address; N: indicates a new object, C: indicates a cached object from a scope. ```text 0: Factory.Container.cycleDemo<CycleDemo> = N:105553131389696 1: Factory.Container.aService<AServiceType> = N:105553119821680 2: Factory.Container.implementsAB<AServiceType & BServiceType> = N:105553119821680 3: Factory.Container.networkService<NetworkService> = N:105553119770688 1: Factory.Container.bService<BServiceType> = N:105553119821680 2: Factory.Container.implementsAB<AServiceType & BServiceType> = C:105553119821680 ``` -------------------------------- ### Reset Container in setUp for Fresh State Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Reset the container caches in setUp to start from scratch, eliminating the need for teardown. This is safe after the app has launched and is idling. ```swift final class FactoryCoreTests: XCTestCase { override func setUp() { Container.shared.reset() Container.shared.setupMocks() } func testNoAccounts() throws { ... } } ``` -------------------------------- ### Shared Scope Example Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Scopes.md Define a shared factory and demonstrate how instances are reused while strong references existсь, but a new instance is created after all strong references are nil. ```swift extension Container { var sharedService: Factory<MyServiceType> { self { MyService() }.shared } } ``` ```swift // resolution var a = container.sharedService() var b = container.sharedService() // zap all strong references a = nil b = nil // resolve it again var c = container.sharedService() ``` -------------------------------- ### Package.swift test target setup for FactoryKitDynamic Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Shows the correct and incorrect ways to configure a test target for a multi-module app using FactoryKitDynamic. The correct approach links FactoryKitDynamic and includes a copy of ContainerTrait.swift, while the incorrect approach adds FactoryTesting which pulls in a second, disconnected copy of FactoryKit. ```swift // DO THIS for multi-module apps using FactoryKitDynamic .testTarget(name: "MyAppTests", dependencies: [ "MyApp", "FactoryKitDynamic", // not FactoryKit ]) // ...and add a copy of ContainerTrait.swift as a source file in MyAppTests. // DO NOT DO THIS .testTarget(name: "MyAppTests", dependencies: [ "MyApp", "FactoryKitDynamic", "FactoryTesting", // BAD! Pulls in a second, disconnected copy of FactoryKit. ]) ``` -------------------------------- ### External setup: define factory and apply debug override in autoRegister() Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Modifiers.md A factory definition that keeps only the core logic internally, followed by an external autoRegister() extension that applies debug-only overrides via .onTest. ```swift extension Container { public func myService: Factory<MyServiceType>() { self { MyService() } .singleton } } ``` ```swift extension Container: AutoRegistering { public func autoRegister() { #if DEBUG myService .onTest { MockAnalyticsEngine() } #endif } } ``` -------------------------------- ### Pass Container Instance to View Model in Tests Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Create a new Container instance in setUp and pass it to the view model, allowing isolated testing. This requires the app to be structured to accept a container. ```swift final class FactoryCoreTests: XCTestCase { var container: Container! override func setUp() { container = Container() container.setupMocks() } func testSomething() throws { container.myServiceType.register { MockService() } let model = MyViewModel(container: container) model.load() XCTAssertTrue(model.isLoaded) } } ``` -------------------------------- ### XCTest UI Test with Launch Argument Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md XCTest UI test that launches the app with a launch argument 'mock1' and verifies a static text exists. This is the first part of a UITesting setup where the app's behavior is changed before RunLoop.main starts. ```swift import XCTest final class FactoryDemoUITests: XCTestCase { func testExample() throws { let app = XCUIApplication() app.launchArguments.append("mock1") // passed parameter app.launch() let welcome = app.staticTexts["Mock Number 1! for Michael"] XCTAssert(welcome.exists) } } ``` -------------------------------- ### ContentView using ContentViewModel Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/GettingStarted.md Example view that uses a view model assigned to a StateObject. This is the base code that will be previewed with a mock service. ```swift struct ContentView: View { @StateObject var model = ContentViewModel() var body: some View { Text(model.text()) .padding() } } ``` -------------------------------- ### Factory debug trace output Source: https://github.com/hmlongco/factory/blob/main/README.md Example trace output from Factory's debug mode, showing the dependency tree for a resolution cycle. Each line shows the container, type, and whether the instance was freshly created (F) or returned from cache (C). ```text 0: Factory.Container.cycleDemo<CycleDemo> = F:105553131389696 1: Factory.Container.aService<AServiceType> = F:105553119821680 2: Factory.Container.implementsAB<AServiceType & BServiceType> = F:105553119821680 3: Factory.Container.networkService<NetworkService> = F:105553119770688 1: Factory.Container.bService<BServiceType> = F:105553119821680 2: Factory.Container.implementsAB<AServiceType & BServiceType> = C:105553119821680 ``` -------------------------------- ### XCTest with Container.shared.reset() and MockProvider Source: https://github.com/hmlongco/factory/blob/main/README.md For XCTest, reset the shared container in setUp() to isolate tests. Override the accountProvider with a MockProvider and assert with XCTAssertTrue. ```swift final class FactoryCoreTests: XCTestCase { override func setUp() { super.setUp() Container.shared.reset() } func testLoaded() throws { Container.shared.accountProvider { MockProvider(accounts: .sampleAccounts) } let model = Container.shared.someViewModel() model.load() XCTAssertTrue(model.isLoaded) } // other tests } ``` -------------------------------- ### Chain context modifiers for preview and test services Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Contexts.md Demonstrates chaining multiple context modifiers to specify different service implementations for preview and test contexts. The example uses onPreview and onTest to provide MockService and UnitTestMockService respectively. ```swift container.myServiceType .onPreview { MockService() } .onTest { UnitTestMockService() } ``` -------------------------------- ### Set and remove runtime arguments with FactoryContext and onArg Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Contexts.md Shows how to set and remove runtime arguments with FactoryContext and use onArg to provide context-specific implementations. The example sets a "light" argument, then removes it, and defines fallback and context-specific theme factories. ```swift FactoryContext.setArg("light", forKey: "theme") FactoryContext.removeArg(forKey: "theme") myStyleSystem { StandardTheme() } .onArg("light") { LightTheme() } .onArg("dark") { DarkTheme() } ``` -------------------------------- ### Cached Scope Example Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Scopes.md Define a cached factory and resolve it twice. Both resolutions return the same instance because the scope is cached. ```swift extension Container { var cachedService: Factory<MyServiceType> { self { MyService() }.cached } } ``` ```swift let a = container.cachedService() let b = container.cachedService() ``` -------------------------------- ### View model with @Injected dependency Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/SwiftUI.md Shows a view model using @Injected to obtain its service dependency. This is the pattern used in the earlier StateObject example. ```swift class ContentViewModel: ObservableObject { @Injected(\.myService) private var service ... } ``` -------------------------------- ### Register and reset optional factory dynamically Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Optionals.md Register a concrete provider when a user authenticates, and reset the factory on logout. Registering clears cached values from the scope so subsequent requests get the latest instance. ```swift func authenticated(with user: User) { ... Container.shared.userProviding.register { UserProvider(user: user) } ... } func logout() { ... Container.shared.userProviding.reset() ... } ``` -------------------------------- ### Mock Deep Dependency with MockJSON for Network Layer Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Reach further down the dependency tree by mocking the network service that the AccountLoader depends on. This example uses a JSON string to simulate an empty accounts list. ```swift func testNoAccounts() async throws { let json = #"{ "accounts": [] }"# Container.shared.networking { MockJSON(json) } let model = Container.shared.accountsViewModel() // as before } ``` -------------------------------- ### Explicitly unwrap optional injected dependency (discouraged) Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Modules.md This example shows explicitly unwrapping the optional injected property. It works only if the registration is wired correctly; otherwise it will crash at runtime. The source advises against this approach because it defeats Factory's safety guarantees. ```swift class ViewModel: ObservableObject { @Injected(\.accountLoader) var loader: AccountLoading! @Published var accounts: [Account] = [] func load() { accounts = loader.load() } } ``` -------------------------------- ### Circular dependency detection log output Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Chains.md Example log output when Factory detects a circular dependency. It shows the timestamp, source location, and the message 'FACTORY: Circular dependency on Container.recursiveA'. ```text 2022-12-23 14:57:23.512032-0600 FactoryDemo[47546:6946786] Factory/Factory.swift:393: FACTORY: Circular dependency on Container.recursiveA ``` -------------------------------- ### Registering Dependencies with Transforming Sugar Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Use the transforming sugar to register dependencies directly inside the @Test(.container { ... }) trailing closure, keeping registrations separate from test code. The example registers two services and then resolves them to verify their error values. ```swift struct AppTests { @Test(.container { $0.someService { ErrorService() } $0.someOtherService { OtherErrorService() } }) func testA() async { let service = Container.shared.someService() let otherService = Container.shared.someOtherService() #expect(service.error == "Oops") #expect(otherService.error == "OtherOops") } } ``` -------------------------------- ### Releasing a Container by Reassignment Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Containers.md Shows that reassigning a container releases the previous container and its cached objects. The example creates a MyContainer, caches a service, then replaces the container with a new one, demonstrating that the new container returns a fresh instance while subsequent calls return the same cached instance. ```swift // Create an instance of our cached service. var container = MyContainer() let service1 = container.cachedService() // Repeat, which returns the same cached instance we obtained in service1. let service2 = container.cachedService() assert(service1.id == service2.id) // Replace the existing shared container with a new one. container = MyContainer() // Trying again gets a new instance since the old container and cache was released. let service3 = container.cachedService() assert(service1.id != service3.id) // Repeat and receive the same cached instance we obtained in service3. let service4 = container.cachedService() assert(service3.id == service4.id) ``` -------------------------------- ### Multiple previews with PreviewProvider Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Previews.md Shows how to create multiple previews with different data by instantiating view models and passing them as parameters, using the traditional PreviewProvider syntax. ```swift struct ContentView_Previews: PreviewProvider { static var previews: some View { Group { Container.shared.myService { MockServiceN(4) } let vm1 = ContentViewModel() ContentView(viewModel: vm1) Container.shared.myService { MockServiceN(8) } let vm2 = ContentViewModel() ContentView(viewModel: vm2) } } } ``` -------------------------------- ### Multiple registrations in a container for preview Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Previews.md Shows how to register multiple services in a container within a #Preview block. ```swift #Preview { Container.shared { $0.myService { MockServiceN(4) } $0.anotherService { MockAnotherService() } } ContentView() } ``` -------------------------------- ### Multiple previews with #Preview macro Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Previews.md Shows how to create multiple previews with different data using the #Preview macro, each running in its own context. ```swift #Preview { Container.shared.myService { MockServiceN(4) } ContentView() } #Preview { Container.shared.myService { MockServiceN(0) } ContentView() } ``` -------------------------------- ### Use #Preview macro to mock service Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Previews.md Shows the same mocking approach using the new #Preview macro introduced in Xcode 15. ```swift #Preview { Container.shared.myService { MockServiceN(4) } ContentView() } ``` -------------------------------- ### Create a list of key paths for processors Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Tags.md Builds a static array of key paths that reference the processor factories. This list is used to retrieve all processors. ```swift extension Container { public static var processors: [KeyPath<Container, Factory<Processor>>] = [ \.processor1, \.processor2, ] } ``` -------------------------------- ### XCTest setUp reset with Container.shared.reset() Source: https://github.com/hmlongco/factory/blob/main/CLAUDE.md Reset the shared container between XCTest tests to wipe registrations and caches. Alternatively, use `Container.shared.manager.push()` and `.pop()` in `tearDown`. ```swift override func setUp() { super.setUp() Container.shared.reset() // wipes registrations + caches // or: Container.shared.manager.push() / .pop() in tearDown } ``` -------------------------------- ### View with StateObject and direct view model initialization Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/SwiftUI.md Shows a view creating its view model directly with StateObject, since the view model manages its own dependencies. ```swift struct ContentView: View { @StateObject private var viewModel = ContentViewModel() var body: some View { ... } } ``` -------------------------------- ### Define a Factory with Convenience Syntax Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Design.md Defines a Factory for MyServiceType using the convenience syntax on a Container extension. This is the recommended way to create a factory instead of using the formal definition. ```swift extension Container { var myService: Factory<MyServiceType> { self { MyService() } } } ``` -------------------------------- ### Resolve dependencies by type Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Tags.md Shows how to resolve all dependencies conforming to a specific type, another common tagging approach. ```swift let processors = container.resolve(Processing.self) ``` -------------------------------- ### Alternative implementation using cached scope Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Scopes.md Shows an alternative to graph scope using cached scope, where anyone requesting commonProviding gets the same shared reference. ```swift extension Container { // the root var consumer: Factory<ProtocolConsumer> { self { ProtocolConsumer() } } // the interfaces var idProvider: Factory<IDProviding> { self { commonProviding() } } var valueProvider: Factory<ValueProviding> { self { commonProviding() } } // the common implementation private var commonProviding: Factory<MyService> { self { MyService() }.cached } } ``` -------------------------------- ### UI test with launch argument Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Contexts.md UI test that launches the app with the launch argument "mock1" and verifies the expected mock text appears. ```swift import XCTest final class FactoryDemoUITests: XCTestCase { func testExample() throws { let app = XCUIApplication() app.launchArguments.append("mock1") app.launch() let welcome = app.staticTexts["Mock Number 1! for Michael"] XCTAssert(welcome.exists) } } ``` -------------------------------- ### Archive Common scheme for iOS Simulator Source: https://github.com/hmlongco/factory/blob/main/FactoryDemo/Modules/xcarchive.txt Creates an xcarchive for the Common scheme targeting the iOS Simulator. Uses SKIP_INSTALL=NO and BUILD_LIBRARY_FOR_DISTRIBUTION=YES to prepare the framework for distribution. ```bash xcodebuild archive -scheme Common -destination "generic/platform=iOS Simulator" -sdk iphonesimulator -archivePath ./build/common.xcarchive SKIP_INSTALL=NO BUILD_LIBRARY_FOR_DISTRIBUTION=YES ``` -------------------------------- ### Constructor injection with Factory Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Registrations.md Shows how to inject a dependency by calling the Factory for the required service. The constructed service receives the cached service instance. ```swift extension Container { var constructedService: Factory<MyConstructedService> { self { MyConstructedService(service: self.cachedService()) } } var cachedService: Factory<MyServiceType> { self { MyService() }.cached } } ``` -------------------------------- ### Mock Deep Dependency with MockError for Network Layer Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Mock the network service to return an error, testing the error path deep in the dependency tree. This example uses MockError(404) to simulate a failure. ```swift func testNoAccounts() async throws { Container.shared.networking { MockError(404) } let model = Container.shared.accountsViewModel() // as before } ``` -------------------------------- ### Define protocol, Factory, and private implementation in same module Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Modules.md Shows the pattern for defining a protocol, its Factory, and a private implementation in the same module. The Factory is public and returns a private Network instance, so consumers only see the Networking protocol. ```swift // Public Protocol public protocol Networking { func load<T>() async throws -> T } // Public Factory extension Container { public var network: Factory<Networking> { self { Network() } } } // Private Implementation private class Network: Networking { public func load<T>() async throws -> T { ... } } ``` -------------------------------- ### Using Multiple Container Traits in a Test Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Use multiple container traits in a single @Test attribute to access dependencies from several containers within one test. The example shows a test that resolves services from both Container and CustomContainer. ```swift struct AppTests { @Test(.container, .customContainer) func testA() async { let sut1 = Container.shared.service() let sut2 = CustomContainer.shared.service() ... } } ``` -------------------------------- ### Factory 1.0 resolution syntax Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Additional/Migration.md Shows the Factory 1.0 resolution syntax for comparison with the current shared container approach. ```swift // Factory 1.0 resolution let service = Container.service() ``` -------------------------------- ### Archive Networking scheme for iOS Simulator Source: https://github.com/hmlongco/factory/blob/main/FactoryDemo/Modules/xcarchive.txt Creates an xcarchive for the Networking scheme targeting the iOS Simulator. Uses SKIP_INSTALL=NO and BUILD_LIBRARY_FOR_DISTRIBUTION=YES to prepare the framework for distribution. ```bash xcodebuild archive -scheme Networking -destination "generic/platform=iOS Simulator" -sdk iphonesimulator -archivePath ./build/networking.xcarchive SKIP_INSTALL=NO BUILD_LIBRARY_FOR_DISTRIBUTION=YES ``` -------------------------------- ### Use promised() for safe optional factory Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Modules.md Use promised() to get a factory that triggers a fatalError in debug mode when the dependency is unregistered, but returns nil in release builds. This avoids crashes in production while still alerting developers during development. ```swift extension Container { public var accountLoader: Factory<AccountLoading?> { promised() } } ``` -------------------------------- ### Initialize from Passed Container Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Resolutions.md Passes a container instance to the view model and initializes a service from that container in the initializer. ```swift class ContentViewModel: ObservableObject { let service2: MyServiceType init(container: Container) { service2 = container.service() } } ``` -------------------------------- ### Register a new Factory closure with shortcut syntax Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/GettingStarted.md Shortcut syntax for registering a new closure on an existing factory, equivalent to the register method. ```swift container.service { MockService() } ``` -------------------------------- ### Set preview context override Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Contexts.md Sets a mock service for SwiftUI previews. Use this to provide preview-specific dependencies. ```swift container.myServiceType .onPreview { MockService() } ``` -------------------------------- ### Re-export FactoryKit with public import Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Modules.md Uses Swift 5.9's public import to re-export FactoryKit from Services, so any module that imports Services automatically gets FactoryKit symbols without an explicit import. The accountLoader Factory uses promised() to defer resolution until the application wires the registrations together. ```swift // Services/DependencyContainer.swift public import FactoryKit extension Container { public var accountLoader: Factory<AccountLoading?> { promised() } } ``` -------------------------------- ### Composition Root with Container Factories Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Resolutions.md Implements the Composition Root pattern by defining container factories and using them to provide dependencies to a view model in the app entry point. ```swift extension Container { var constructedService: Factory<MyConstructedService> { self { MyConstructedService(service: self.cachedService()) }.singleton } var cachedService: Factory<MyServiceType> { self { MyService() }.cached } } @main struct FactoryDemoApp: App { let viewModel = MyViewModel(service: Container.shared.constructedService()) var body: some Scene { WindowGroup { NavigationView { ContentView(viewModel: viewModel) } } } } ``` -------------------------------- ### Resolve tagged dependencies Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Tags.md Shows how to resolve a list of dependencies tagged with a string. This is a common pattern in other DI systems. ```swift let processors = container.resolve(tagged: "processor") ``` -------------------------------- ### Implement an adaptor protocol for third-party libraries Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Modules.md Defines a public protocol, a public factory registration, and a private adaptor implementation to wrap a third-party analytics library. Use this pattern to provide an agnostic interface to external services like analytics or feature managers. ```swift // Public Protocol public protocol Analytics { func event(location: String, name: String) } // Public Factory extension Container { public var analytics: Factory<Analytics> { self { AnalyticsAdaptor() } } } // Private Implementation private class AnalyticsAdaptor: Analytics { public func event(location: String, name: String) { // talk to analytics library } } ``` -------------------------------- ### Change a registration to a mock using simplified syntax in a test method Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Shows replacing a registration with a mock using the simplified syntax without .register. Useful for testing against unstable data and verifying error states. ```swift func testNoAccounts() async { // register a mock Container.shared.accountLoading { MockAccountError(404) } // no .register needed // instantiate the model that uses the mock let model = Container.shared.accountsViewModel() // and test... await model.load() XCTAssertFalse(model.isLoaded) XCTAssertTrue(model.isError) } ``` -------------------------------- ### Append a new processor during auto-registration Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Tags.md Shows how to add a new processor to the list during automatic registration, using the AutoRegistering protocol. ```swift extension Container: AutoRegistering { func autoRegister() { Container.processors.append(\.processor3) } var processor3: Factory<Processor> { self { Processor3() } } } ``` -------------------------------- ### Configure Test Target with FactoryTesting Source: https://github.com/hmlongco/factory/blob/main/README.md Shows the correct and incorrect ways to configure a test target for Swift Testing. Use FactoryTesting in the test target, but do not copy FactoryKit into the test target to avoid duplicate factories and indeterminate behavior. ```swift // DO THIS .testTarget(name: "MyAppTests", dependencies: [ "MyApp", "FactoryTesting" ]) ``` ```swift // DO NOT DO THIS .testTarget(name: "MyAppTests", dependencies: [ "MyApp", "FactoryKit", // BAD!!! "FactoryTesting" ]) ``` -------------------------------- ### AutoRegistering Cross-Module Wiring Source: https://github.com/hmlongco/factory/blob/main/CLAUDE.md Implements AutoRegistering to wire cross-module dependencies from the app target. ```swift extension Container: @retroactive AutoRegistering { func autoRegister() { accountLoader.register { AccountLoader() } // wired from the app target } } ``` -------------------------------- ### Trace output for direct CycleDemo instantiation Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Cycle.md Trace output when CycleDemo is created directly. It shows two separate resolution cycles (indicated by the '0:' prefix) for aService and bService, each resolving its own implementsAB and networkService instances. ```text 0: Container.aService<AServiceType> = N:105553119775792 1: Container.implementsAB<AServiceType & BServiceType> = N:105553119775792 2: Container.networkService<NetworkService> = N:105553119821280 0: Container.bService<BServiceType> = N:105553119821360 1: Container.implementsAB<AServiceType & BServiceType> = N:105553119821360 2: Container.networkService<NetworkService> = N:105553119821600 ``` -------------------------------- ### Resolve processors using key paths Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Tags.md Defines a method that maps the key paths to actual Processor instances, returning a type-safe array. ```swift extension Container { public func processors() -> [Processor] { Container.processors.map { self[keyPath: $0]() } } } ``` -------------------------------- ### Pass Container to View Model and Resolve Service Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Design.md Shows how to pass a container instance to a view model and initialize a service from it. This pattern is the primary rationale for the Factory 2.0 changes. ```swift class ContentViewModel { let myService: MyServiceType init(container: Container) { myService = container.myService() } } ``` -------------------------------- ### Custom container with factory definitions Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Registrations.md Shows how to define factories inside a custom container conforming to SharedContainer. Includes a warning against using lazy var for factories due to reference cycles. ```swift final class ServiceContainer: SharedContainer { // CONFORMANCE static var shared = ServiceContainer() var manager = ContainerManager() // DEFINE FACTORY var service1: Factory<MyServiceType> { self { MyService() } } // DON'T DO THIS lazy var service2: Factory<MyServiceType> = self { MyService() } } ``` -------------------------------- ### Import FactoryTesting Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md The `FactoryTesting` module provides container traits. Add it as a dependency to your test target. ```swift import Testing import FactoryTesting ``` -------------------------------- ### AutoRegister with Launch Argument Check Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Uses Factory's auto registration to check launch arguments and override a service registration when 'mock1' is present. The registration is wrapped in #if DEBUG to limit it to debug builds. ```swift import Foundation import Factory extension Container: AutoRegistering { public func autoRegister() { #if DEBUG if ProcessInfo().arguments.contains("mock1") { myServiceType { MockServiceN(1) } } #endif } } ``` -------------------------------- ### Composition Root with Container Extension Source: https://github.com/hmlongco/factory/blob/main/README.md Use a Composition Root structure where the container provides required dependencies to a constructor. The container extension defines factories for MyRepositoryType and Networking, and the app entry point uses Container.shared.myRepository() to create the view model. ```swift extension Container { var myRepository: Factory<MyRepositoryType> { self { MyRepository(service: self.networkService()) } } var networkService: Factory<Networking> { self { MyNetworkService() } } } @main struct FactoryDemoApp: App { let viewModel = MyViewModel(repository: Container.shared.myRepository()) var body: some Scene { WindowGroup { NavigationStack { ContentView(viewModel: viewModel) } } } } ``` -------------------------------- ### Basic dependency registration Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Registrations.md Registers a service that returns a new instance each time it is resolved. Uses the concise container helper syntax. ```swift extension Container { var service: Factory<MyServiceType> { self { MyService() } } } ``` -------------------------------- ### SwiftUI preview with onPreview override Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Contexts.md Simplified SwiftUI preview that relies on the onPreview override to provide mock dependencies. ```swift struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } ``` -------------------------------- ### Preview with mock service registration Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/GettingStarted.md Preview provider that registers a mock service on the shared container before displaying ContentView. This overrides the default factory closure so the preview uses MockService2 instead of the original MyService. ```swift struct ContentView_Previews: PreviewProvider { static var previews: some View { Container.shared.myService { MockService2() } ContentView() } } ``` -------------------------------- ### Collect processors from multiple modules Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Tags.md Shows how to append anonymous processor contributions from multiple modules during auto-registration. ```swift extension Container: AutoRegistering { func autoRegister() { Container.processors += ModuleA.availableProcessors() Container.processors += ModuleB.availableProcessors() Container.processors += ModuleC.availableProcessors() } } ``` -------------------------------- ### View model with initializer injection Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/SwiftUI.md Shows a view model that requires its service via an initializer, enabling Factory to provide a fully initialized object. ```swift class ContentViewModel: ObservableObject { private let service: MyServiceType init(service: MyServiceType) self.service = service } ... } ``` -------------------------------- ### Register factories for cycle demo Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Cycle.md Registers the factories for the cycle demo. Note that aService and bService both delegate to the private implementsAB factory, which uses the .graph scope. ```swift extension Container { var cycleDemo: Factory<CycleDemo> { self { CycleDemo() } } var aService: Factory<AServiceType> { self { self.implementsAB() } } var bService: Factory<BServiceType> { self { self.implementsAB() } } private var implementsAB: Factory<AServiceType&BServiceType> { self { ImplementsAB() } .graph } var networkService: Factory<NetworkService> { self { NetworkService() } } var preferences: Factory<Preferences> { self { Preferences() } } } ``` -------------------------------- ### Factory registrations for initializer injection Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/SwiftUI.md Shows Factory registrations for a view model and its service, where the view model is initialized with the service from the container. ```swift extension Container { var contentViewModel: Factory<ContentViewModel> { self { ContentViewModel(service: myService()) } } var myService: Factory<MyServiceType> { self { MyService() } } } ``` -------------------------------- ### Factory 1.x vs 2.0 Registration Comparison Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Additional/Migration.md Side-by-side comparison of Factory 1.x and 2.0 registration definitions. The 1.x version uses a static variable, while the 2.0 version uses a computed variable on the container. ```swift extension Container { // Factory 1.x static var service = Factory<ServiceType> { MyService() } // Factory 2.0 var service: Factory<ServiceType> { self { MyService() } } } ``` -------------------------------- ### AutoRegister with onArg Context Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Simplifies the previous auto-registration approach using the onArg context to conditionally register a mock service when the 'mock1' launch argument is present. Also wrapped in #if DEBUG. ```swift import Foundation import Factory extension Container: AutoRegistering { public func autoRegister() { #if DEBUG myServiceType.onArg("mock1") { MockServiceN(1) } #endif } } ``` -------------------------------- ### Implement AutoRegistering to wire modules Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Modules.md Conforms Container to AutoRegistering in the application that sees all modules, registering a new factory closure for accountLoader. autoRegister is called before any Factory resolution. ```swift import ModuleP import ModuleA import ModuleB extension Container: AutoRegistering { func autoRegister { accountLoader.register { AccountLoader() } ... } } ``` -------------------------------- ### Factory Definition Using Syntactic Sugar Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Additional/Migration.md Uses the syntactic sugar provided by Factory to let the enclosing container create the factory. This is the recommended shorthand for defining a factory on a container. ```swift var service: Factory<ServiceType> { self { MyService() } } ``` -------------------------------- ### Constructor Injection with Factory Source: https://github.com/hmlongco/factory/blob/main/CLAUDE.md Shows constructor injection from the container, where one factory depends on another and uses the .singleton scope. ```swift extension Container { var repo: Factory<Repo> { self { Repo(net: self.network()) } } var network: Factory<Networking> { self { LiveNetwork() }.singleton } } ``` -------------------------------- ### Define an optional Factory Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Optionals.md Declare an optional factory named 'userProviding' that returns 'UserProviding?' and defaults to nil. This allows dynamic registration later. ```swift extension Container { let userProviding = Factory<UserProviding?> { self { nil } } } ``` -------------------------------- ### Instantiate CycleDemo directly Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Cycle.md Creates an instance of CycleDemo directly, bypassing Factory's resolution. This is used to illustrate the trace output that follows, showing separate resolution cycles for each property wrapper. ```swift let demo = CycleDemo() ``` -------------------------------- ### Manual test detection with XCTestConfigurationFilePath Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Contexts.md Manual approach to detect unit tests by checking the XCTestConfigurationFilePath environment variable. This does not work when tests are launched from the command line using swift test. ```swift if ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil { container.analytics.register { MockAnalyticsEngine() } } ``` -------------------------------- ### Correct vs Incorrect Test Target Dependencies Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Correct and incorrect test target configurations. Including `FactoryKit` in the test target can lead to duplicate factories and indeterminate behavior. ```swift // DO THIS .testTarget(name: "MyAppTests", dependencies: [ "MyApp", "FactoryTesting" ]) // DO NOT DO THIS .testTarget(name: "MyAppTests", dependencies: [ "MyApp", "FactoryKit", // BAD!!! "FactoryTesting" ]) ``` -------------------------------- ### Resetting specific singleton factories Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Demonstrates resetting a specific factory's cache, resetting only the scope cache, or registering a new instance to clear the existing one. ```swift // reset everything for that factory Container.shared.someSingletonFactory.reset() // reset just the scope cache Container.shared.someSingletonFactory.reset(options: .scope) // or simply register a new instance Container.shared.someSingletonFactory.register { MyNewMock() } ``` -------------------------------- ### Factory 1.0 @Injected syntax Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Additional/Migration.md Shows the Factory 1.0 version of the @Injected property wrapper for reference. ```swift // Factory 1.0 version for reference @Injected(Container.service) var service: ServiceType ``` -------------------------------- ### Swift Testing with .container trait and MockProvider Source: https://github.com/hmlongco/factory/blob/main/README.md Use the @Suite(.container) trait to give each test a fresh instance of the shared container. Override the accountProvider with a MockProvider to simulate loading, empty, and error states, then assert on the view model's state. ```swift @Suite(.container) // note container trait struct FactoryTests { @Test func testLoaded() async { Container.shared.accountProvider { MockProvider(accounts: .sampleAccounts) } let model = Container.shared.someViewModel() model.load() #expect(model.isLoaded) } @Test func testEmpty() async { Container.shared.accountProvider { MockProvider(accounts: []) } let model = Container.shared.someViewModel() model.load() #expect(model.isEmpty) } @Test func testErrors() async { Container.shared.accountProvider { MockProvider(error: .notFoundError) } let model = Container.shared.someViewModel() model.load() #expect(model.errorMessage == "Some Error") } } ``` -------------------------------- ### Set onArgs override for multiple arguments Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Contexts.md Sets the same factory for multiple launch arguments. Use onArgs when any of the listed arguments should trigger the same override. ```swift myServiceType .onArgs(["mock0", "mock1", "mock3"]) { EmptyService() } ``` -------------------------------- ### Context Overrides for Environments Source: https://github.com/hmlongco/factory/blob/main/CLAUDE.md Shows context-based auto-overrides for environments: onTest, onPreview, onDebug (DEBUG-only), onArg (runtime), onSimulator, and onDevice. ```swift container.analytics .onTest { MockAnalytics() } // DEBUG-only .onPreview { MockAnalytics() } // DEBUG-only .onDebug { MockAnalytics() } // DEBUG-only .onArg("mock1") { MockServiceN(1) } // available at runtime .onSimulator { ... } .onDevice { ... } ``` -------------------------------- ### Tag with priority using a struct Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Tags.md Defines a Tag struct that includes a key path and a priority, and shows how to sort processors by priority when resolving. ```swift struct Tag<T> { let path: KeyPath<Container, Factory<T>> let priority: Int } extension Container { static var processors: [Tag<Processor>] = [ Tag(path: \.processor1, priority: 20), Tag(path: \.processor2, priority: 10), ] func processors() -> [Processor] { Container.processors .sorted(by: { $0.priority < $1.priority }) .map { self[keyPath: $0.path]() } } } ``` -------------------------------- ### Reference another container's service with full path Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Containers.md Shows how to reference a service from another container by using the full container.factory path, here accessing Container.shared.optionalService() inside a factory for AnotherService. ```swift extension PaymentsContainer { var anotherService: Factory<AnotherService> { self { AnotherService(using: Container.shared.optionalService()) } } } ``` -------------------------------- ### Update view model's service dependency for preview Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Previews.md Shows how to override a service dependency in a container within a PreviewProvider to set up a specific state for a preview. ```swift // the view model class ContentViewModel: ObservableObject { @Injected(\.myService) private var service ... func load() async { let results = await service.load() ... } } // the view struct ContentView: View { @StateObject var viewModel = ContentViewModel() var body: some View { ... } } // the preview struct ContentView_Previews: PreviewProvider { static var previews: some View { Container.shared.myService { MockServiceN(4) } ContentView() } } ``` -------------------------------- ### AutoRegistering on a custom container Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Containers.md Conform a custom container to AutoRegistering and implement autoRegister() to register instances before the first service resolution on that container. Called once prior to the very first Factory service resolution. ```swift extension MyContainer: AutoRegistering { func autoRegister() { someService { ModuleB.SomeService() } } } ``` -------------------------------- ### Define a Factory with a closure Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/GettingStarted.md Shows the basic registration of a Factory<ServiceType> in a Container extension. The closure returns a new MyService() instance each time the factory is resolved. ```swift extension Container { var service: Factory<ServiceType> { self { MyService() } } } ``` -------------------------------- ### Apply same dependency to multiple contexts with context modifier Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Contexts.md Shows how to apply the same dependency implementation to multiple contexts using the context modifier with an array of contexts. Here, MockService is used for both simulator and test contexts. ```swift container.myServiceType .context(.simulator, .test) { MockService() } ``` -------------------------------- ### Preview overriding myService with register (pre-3.2) Source: https://github.com/hmlongco/factory/blob/main/README.md The pre-3.2 way to override a factory in a preview using the register function. The new callAsFunction syntax is cleaner and is used going forward. ```swift #Preview { // the old way, prior to 3.2 let _ = Container.shared.myService.register { MockService2() } ContentView() } ``` -------------------------------- ### Trace output with singleton scope for implementsAB Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Cycle.md Trace output after changing implementsAB's graph scope to singleton. Now aService and bService resolve to the same instance, and implementsAB is cached (indicated by 'C:') on the second resolution. ```text 0: Container.aService<AServiceType> = N:105553118258000 1: Container.implementsAB<AServiceType & BServiceType> = N:105553118258000 2: Container.networkService<NetworkService> = N:105553118258480 0: Container.bService<BServiceType> = N:105553118258000 1: Container.implementsAB<AServiceType & BServiceType> = C:105553118258000 ``` -------------------------------- ### Define classes and protocols for cycle demo Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Cycle.md Defines the classes and protocols involved in the resolution cycle: CycleDemo depends on two protocols implemented by ImplementsAB, which requires a NetworkService, which in turn wants a Preferences object. ```swift class CycleDemo { @Injected(\.aService) var aService: AServiceType @Injected(\.bService) var bService: BServiceType } public protocol AServiceType: AnyObject { var id: UUID { get } } public protocol BServiceType: AnyObject { var text: String } class ImplementsAB: AServiceType, BServiceType { @Injected(\.networkService) var networkService var id: UUID = UUID() var text: String = "AB" } class NetworkService { @LazyInjected(\.preferences) var preferences } class Preferences { // just a demo class } ``` -------------------------------- ### Formal Factory registration Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Registrations.md Registers a service using the full formal definition, constructing the Factory with a reference to its enclosing container. ```swift extension Container { var service: Factory<MyServiceType> { Factory(self) { MyService() } } } ``` -------------------------------- ### Define and register a plain actor Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Actors.md Defines a plain actor and registers it with Factory. The actor's initializer is nonisolated, so it can be built synchronously from any context. ```swift actor OrdinaryActor { private var count = 0 func increment() -> Int { count += 1 return count } } extension Container { var ordinaryActor: Factory<OrdinaryActor> { self { OrdinaryActor() } } } ``` -------------------------------- ### Static container property for service Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/GettingStarted.md Alternative approach using a static property on the container to provide a service instance. This is contrasted with the container-based dependency injection approach. ```swift extension Container { static var myService: MyServiceType { MyService() } } ``` -------------------------------- ### Define Factory registrations for processors Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Tags.md Defines two Factory properties for Processor types in a container extension. These are the registrations that will be collected later. ```swift extension SharedContainer { var processor1: Factory<Processor> { self { Processor1() } } var processor2: Factory<Processor> { self { Processor2() } } } ``` -------------------------------- ### Set test context override with onTest Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Contexts.md Shortcut for setting a mock analytics engine for the test context. Equivalent to .context(.test). ```swift container.analytics .onTest { MockAnalyticsEngine() } ``` -------------------------------- ### Register a New Factory for Actor-Isolated Factory Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/SwiftUI.md Shows how to register a new factory for an actor-isolated factory. The closure must also be annotated with @MainActor. ```swift Container.shared.contentViewModel.register { ContentViewModel() } ``` -------------------------------- ### Reset Factory and Container Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Containers.md Resets a single factory, all registrations and caches, or uses the shortcut to reset everything. ```swift container.myService.reset() // resets this factory only container.manager.reset() // clears all registrations and caches container.reset() // shortcut, same as above ``` -------------------------------- ### Using resolveOnMainActor and resolveOnGlobalActor with ParameterFactory Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Actors.md Shows that ParameterFactory has the same two functions, with the runtime parameter threaded through. The first call passes documentID to resolveOnMainActor, and the second passes url as parameters to resolveOnGlobalActor. ```swift Task.detached { let viewModel = await Container.shared.editorViewModel.resolveOnMainActor(documentID) let manager = await Container.shared.importer.resolveOnGlobalActor(BackgroundActor.shared, parameters: url) } ``` -------------------------------- ### Change a registration to a mock in a test method Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Shows replacing a registration with a mock using the standard .register method inside a unit test. Useful for testing against stable data and verifying behavior. ```swift Container.shared.accountLoading.register { MockNoAccounts() } ```