### UI Test Launch Argument Setup Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Contexts.md Example of setting up launch arguments in an XCTestCase to trigger specific application behaviors defined by Factory contexts. ```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) } } ``` -------------------------------- ### SwiftUI #Preview Using Container Setup Mocks Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Previews.md Shows how to use the `setupMocks()` extension function within a `#Preview` block to apply common mock configurations. This example returns `EmptyView` to integrate with the preview syntax. ```swift extension Container { func setupMocks() -> EmptyView { myService { MockServiceN(4) } sharedService { MockService2() } return EmptyView() } } #Preview { Container.shared.setupMocks() ContentView() } ``` -------------------------------- ### FactoryKit Container Setup for Mocks Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Previews.md Defines a helper function `setupMocks()` within a `Container` extension to centralize common mock registrations. This simplifies setup for previews and tests. ```swift extension Container { func setupMocks() { myService { MockServiceN(4) } sharedService { MockService2() } } } ``` -------------------------------- ### Factory 1.0 Resolution Example Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Additional/Migration.md This is a reference example of how services were resolved in Factory 1.0. ```swift // Factory 1.0 resolution let service = Container.service() ``` -------------------------------- ### Push and Pop State for Isolated Tests Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Use `push()` in `setUp()` and `pop()` in `tearDown()` to isolate test environments. This ensures each test starts with a clean container state, unaffected by previous tests. ```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) } } ``` -------------------------------- ### Composition Root Example Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Resolutions.md Use the container to provide required dependencies to a constructor when implementing a Composition Root pattern. ```swift extension Container { var constructedService: Factory { self { MyConstructedService(service: self.cachedService()) }.singleton } var cachedService: Factory { self { MyService() }.cached } } @main struct FactoryDemoApp: App { let viewModel = MyViewModel(service: Container.shared.constructedService()) var body: some Scene { WindowGroup { NavigationView { ContentView(viewModel: viewModel) } } } }ß ``` -------------------------------- ### SwiftUI Previews with Multiple View Models and Mocked Services Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Previews.md Illustrates how to create multiple previews, each with different data, by instantiating view models and passing them to the view. This example uses the older `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) } } } ``` -------------------------------- ### Factory Debugging Output Example Source: https://github.com/hmlongco/factory/blob/main/README.md Example output from Factory's debugging feature, showing the dependency injection trace for object instantiation and cache resolution in DEBUG mode. This helps visualize the dependency tree. ```text 0: Factory.Container.cycleDemo = F:105553131389696 1: Factory.Container.aService = F:105553119821680 2: Factory.Container.implementsAB = F:105553119821680 3: Factory.Container.networkService = F:105553119770688 1: Factory.Container.bService = F:105553119821680 2: Factory.Container.implementsAB = C:105553119821680 ``` -------------------------------- ### Unit Testing with XCTest Source: https://github.com/hmlongco/factory/blob/main/README.md Shows how to use Factory with XCTest for unit testing. Includes resetting the container in setUp and mocking dependencies for specific test cases. ```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 } ``` -------------------------------- ### Service Locator Usage in Factory 1.X Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Design.md Example of how a service was accessed using the Service Locator pattern in Factory 1.X. ```swift class ContentViewModel: ObservableObject { var myService = Container.myService() ... } ``` -------------------------------- ### Resetting Container Caches for a Fresh Start Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Use `Container.shared.reset()` in `setUp()` to clear all container caches. This provides a completely fresh state for tests without needing a corresponding `tearDown()` operation. ```swift final class FactoryCoreTests: XCTestCase { override func setUp() { Container.shared.reset() Container.shared.setupMocks() } func testNoAccounts() throws { ... } } ``` -------------------------------- ### Xcode UITesting with Launch Arguments Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Modify application behavior before it starts by appending launch arguments to `XCUIApplication`. This allows for conditional registrations based on test parameters. ```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) } } ``` -------------------------------- ### Handling Multiple Instances of Same Type Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Registrations.md Example of registering multiple distinct factories for the same type (String) to provide different instances. ```swift extension Container { var string1: Factory { self { "String 1" } } var string2: Factory { self { "String 2" } } var string3: Factory { self { "String 3" } } var string4: Factory { self { "String 4" } } } ``` -------------------------------- ### Example Circular Dependency Classes Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Chains.md Defines classes A, B, and C with circular dependencies using @Injected. This setup can lead to infinite loops during instantiation. ```swift class CircularA { @Injected(\.circularB) var circularB } class CircularB { @Injected(\.circularC) var circularC } class CircularC { @Injected(\.circularA) var circularA } ``` -------------------------------- ### Factory 1.0 @Injected Example Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Additional/Migration.md This is a reference example of the @Injected property wrapper in Factory 1.0. ```swift // Factory 1.0 version for reference @Injected(Container.service) var service: ServiceType ``` -------------------------------- ### Define a Factory in Container Source: https://github.com/hmlongco/factory/blob/main/CLAUDE.md Defines a factory for a service within a container. This is the basic setup for registering a dependency. ```swift import FactoryKit extension Container { var myService: Factory { self { MyService() } // sugar for Factory(self) { ... } } } ``` -------------------------------- ### Conditional Registration with Launch Arguments Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Use Factory's auto-registration feature within your application to check launch arguments and conditionally register services. This example demonstrates checking for the "mock1" argument in a DEBUG build. ```swift import Foundation import Factory extension Container: AutoRegistering { public func autoRegister() { #if DEBUG if ProcessInfo().arguments.contains("mock1") { myServiceType { MockServiceN(1) } } #endif } } ``` -------------------------------- ### Defining Scoped Services Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Registrations.md Examples of defining different scopes for services: standard (transient), cached, singleton, shared, and custom scopes like .session. ```swift extension Container { var standardService: Factory { self { MyService() } } var cachedService: Factory { self { MyService() } .cached } var singletonService: Factory { self { SimpleService() } .singleton } var sharedService: Factory { self { MyService() } .shared .decorator { print("DECORATING \($0.id)") } } var customScopedService: Factory { self { SimpleService() } .scope(.session) } } ``` -------------------------------- ### Static Factory Registration (Deprecated) Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Registrations.md Example of a static Factory registration using a shared container. This method is deprecated and not compatible with Injected property wrappers. ```swift extension Container { static var oldSchool: Factory { Factory(shared) { School() } } } let school = Container.oldSchool ``` -------------------------------- ### Composition Root with Factory Source: https://github.com/hmlongco/factory/blob/main/README.md Define factories for repositories and network services within a Container extension. This setup is typically used in a Composition Root to provide dependencies to your application's components. ```swift extension Container { var myRepository: Factory { self { MyRepository(service: self.networkService()) } } var networkService: Factory { self { MyNetworkService() } } } @main struct FactoryDemoApp: App { let viewModel = MyViewModel(repository: Container.shared.myRepository()) var body: some Scene { WindowGroup { NavigationStack { ContentView(viewModel: viewModel) } } } } ``` -------------------------------- ### Trace Log of a Circular Dependency Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Chains.md A sample trace log output from FactoryKit showing the sequence of dependencies that form a circular chain, starting from the initial request and cycling back. ```text 0: FactoryKit.Container.circularA 1: FactoryKit.Container.circularB 2: FactoryKit.Container.circularC 3: FactoryKit.Container.circularA ``` -------------------------------- ### Parameter Factory for Services with Parameters Source: https://github.com/hmlongco/factory/blob/main/CLAUDE.md Demonstrates how to use `ParameterFactory` for services that require parameters during initialization. Note the absence of property-wrapper support for this. ```swift extension Container { var paramService: ParameterFactory { self { ParamService(value: $0) } } } let s = Container.shared.paramService(42) ``` -------------------------------- ### SwiftUI Multiple #Previews with Different Mocked Services Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Previews.md Demonstrates creating multiple, independent previews using the `#Preview` macro, each configured with a different mocked service. This approach is cleaner for distinct preview states. ```swift #Preview { Container.shared.myService { MockServiceN(4) } ContentView() } #Preview { Container.shared.myService { MockServiceN(0) } ContentView() } ``` -------------------------------- ### Registering a Mock Service for Previews (Newer Syntax) Source: https://github.com/hmlongco/factory/blob/main/README.md Use this syntax to register a mock service for previews, overriding the default implementation. This is the recommended approach for Factory 3.2.0 and later. ```swift #Preview { Container.shared.myService { MockService2() } ContentView() } ``` -------------------------------- ### Registering a Factory for Multiple Contexts Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Contexts.md Demonstrates how to register a single factory implementation that should be used across multiple specified contexts, such as both `.simulator` and `.test` environments. This simplifies configuration when the same dependency is needed in several scenarios. ```swift container.myServiceType .context(.simulator, .test) { MockService() } ``` -------------------------------- ### SwiftUI #Preview with Mocked Service Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Previews.md Demonstrates using the newer `#Preview` macro (Xcode 15+) to register a mock service for a SwiftUI view. This is a more concise way to achieve the same result as the `PreviewProvider`. ```swift #Preview { Container.shared.myService { MockServiceN(4) } ContentView() } ``` -------------------------------- ### Cross-Module Wiring with AutoRegistering Source: https://github.com/hmlongco/factory/blob/main/CLAUDE.md Explains how to use `AutoRegistering` for wiring dependencies across different modules. This allows for centralized registration of components. ```swift extension Container: @retroactive AutoRegistering { func autoRegister() { accountLoader.register { AccountLoader() } // wired from the app target } } ``` -------------------------------- ### Register a Mock Service Source: https://github.com/hmlongco/factory/blob/main/CLAUDE.md Shows how to register a mock implementation for a service, useful for testing. This overrides the default registration. ```swift Container.shared.myService.register { MockService() } ``` -------------------------------- ### Registering Dependencies for Specific Launch Arguments Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Contexts.md Register different services based on specific launch arguments. This is useful for UI testing and simulating various application states. ```swift import Foundation import Factory extension Container: AutoRegistering { public func autoRegister() { #if DEBUG myServiceType .onArg("mock0") { EmptyService() } .onArg("mock1") { MockServiceN(1) } .onArg("error") { MockError(404) } #endif } } ``` -------------------------------- ### Example Class with Optional Injected Property Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Chains.md Illustrates a class 'RecursiveC' where the circularly dependent property 'a' is an optional. This can be a step towards resolving retain cycles. ```swift class RecursiveC { @Injected(\.recursiveA) var a: RecursiveA? init() {} } ``` -------------------------------- ### Registering a Mock Service for Previews (Older Syntax) Source: https://github.com/hmlongco/factory/blob/main/README.md This snippet demonstrates the older syntax for registering a mock service prior to Factory 3.2.0. It involves explicitly calling the register function. ```swift #Preview { // the old way, prior to 3.2 let _ = Container.shared.myService.register { MockService2() } ContentView() } ``` -------------------------------- ### Registering a Dependency for SwiftUI Previews Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Contexts.md Use the .onPreview shortcut to register a dependency that will be used exclusively when running SwiftUI Previews. ```swift container.myServiceType .onPreview { MockService() } ``` -------------------------------- ### XCTest Container Reset Source: https://github.com/hmlongco/factory/blob/main/CLAUDE.md Reset the shared container before each test in XCTest to ensure isolation. Alternatively, use push/pop operations within `setUp` and `tearDown`. ```swift override func setUp() { super.setUp() Container.shared.reset() // wipes registrations + caches // or: Container.shared.manager.push() / .pop() in tearDown } ``` -------------------------------- ### Conditional Factory Registration for Different Environments Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Contexts.md Illustrates how to provide distinct dependency implementations for different testing and preview environments using `onPreview` and `onTest` modifiers. This is useful for injecting mock services during development and testing. ```swift container.myServiceType .onPreview { MockService() } .onTest { UnitTestMockService() } ``` -------------------------------- ### SwiftUI View Modifier Example Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Modifiers.md Demonstrates how view modifiers in SwiftUI can behave similarly to FactoryKit's scope, where the innermost bound property takes precedence. ```swift struct innerView: View { var body: some View { Text("Hello") .foregroundColor(.red) } } struct outerView: View { var body: some View { innerView() .foregroundColor(.green) } } ``` -------------------------------- ### Defining Singleton and Session Scopes Source: https://github.com/hmlongco/factory/blob/main/README.md Demonstrates how to define a singleton scope for a network service and a session scope for another service within a Factory container. ```swift extension Container { var networkService: Factory { self { NetworkProvider() } .singleton } var myService: Factory { self { MyService() } .scope(.session) } } ``` -------------------------------- ### Defining Scopes with Modifier Syntax Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Additional/Migration.md Scopes are now defined using a modifier syntax on the Factory. This example shows how to define singleton and shared scopes with an optional decorator. ```swift extension Container { var singletonService: Factory { self { MyService() }.singleton } var decoratedSharedService: Factory { self { MyService() } .shared .decorator { print("DECORATING \($0.id)") } } } ``` -------------------------------- ### Dynamic Registration and Resetting of Optional Factories Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Optionals.md Demonstrates how to dynamically register a concrete implementation for an optional factory and how to reset it. This allows dependencies to be provided based on application state. ```swift func authenticated(with user: User) { ... Container.shared.userProviding.register { UserProvider(user: user) } ... } func logout() { ... Container.shared.userProviding.reset() ... } ``` -------------------------------- ### Factory with Singleton Scope and Test Override Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Modifiers.md A factory definition that is a singleton and includes a test-specific override for analytics. This setup is common for services that should persist and have test variations. ```swift public func myService: Factory() { self { MyService() } .singleton .onTest { MockAnalyticsEngine() } } ``` -------------------------------- ### SwiftUI #Preview with Multiple Mocked Services Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Previews.md Shows how to register multiple mock services within a single `#Preview` block using a closure on `Container.shared`. This is helpful when a view depends on several different mocked dependencies. ```swift #Preview { Container.shared { $0.myService { MockServiceN(4) } $0.anotherService { MockAnotherService() } } ContentView() } ``` -------------------------------- ### CycleDemo Initialization Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Cycle.md Demonstrates the initialization of a class with two distinct injected properties, triggering separate resolution cycles. ```swift let demo = CycleDemo() ``` -------------------------------- ### FactoryKit Circular Dependency Error Log Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Chains.md An example of the error message logged by FactoryKit when a circular dependency is detected. It indicates the container and the specific dependency causing the issue. ```text 2022-12-23 14:57:23.512032-0600 FactoryDemo[47546:6946786] Factory/Factory.swift:393: FACTORY: Circular dependency on Container.recursiveA ``` -------------------------------- ### Indirect Container Access Example Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Illustrates how `@Injected` property wrappers indirectly access `Container.shared`, and how TaskLocal solves this by providing an isolated container for each test when using the `.container` trait. ```swift class MyClass { @Injected(\.myService) var service // accesses Container.shared internally ... } ``` -------------------------------- ### Define Public Factory in Services Module Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Modules.md When a module needs to be independent of FactoryKit, define its factories in a separate 'Services' module. This example shows how the `accountLoader` factory is exposed publicly. ```swift extension Container { public var accountLoader: Factory { self { nil } } } ``` -------------------------------- ### Container Registration and Scope Management Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Containers.md Demonstrates creating a custom container and registering a service with a cached scope. It also shows how to resolve services from both a specific container instance and the shared default container. ```swift let containerA = MyContainer() containerA.cachedService { MockService() } // Will have a MockService let service1 = containerA.cachedService() // Will have a new or previously cached instance of ServiceType let service2 = MyContainer.shared.cachedService() ``` -------------------------------- ### Initialize Service from Passed Container Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Resolutions.md Pass an instance of a container to a view model and initialize the service from that container. ```swift class ContentViewModel: ObservableObject { let service2: MyServiceType init(container: Container) { service2 = container.service() } } ``` -------------------------------- ### Reference Another Container's Factory Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Containers.md Access factories from other containers by specifying the full `container.factory` path. This example shows how `anotherService` in `PaymentsContainer` uses `optionalService` from the shared container. ```swift extension PaymentsContainer { var anotherService: Factory { self { AnotherService(using: Container.shared.optionalService()) } } } ``` -------------------------------- ### Defining Classes and Protocols for Dependency Injection Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Cycle.md Sets up the structure for dependency injection, defining classes that depend on protocols and other services. ```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 } ``` -------------------------------- ### Define Suite Trait for Tests Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Apply the `.container` trait to an entire test suite. Tests within the suite automatically inherit this trait, simplifying setup for shared container dependencies. ```swift import XCTest import Factory // define container trait for entire suite of tests @Suite(.container) struct AppTests { // test inherits .container trait from suite @Test() func testA() async { ... } // test inherits container trait from suite @Test(arguments: Parameters.allCases) func testB(parameter: Parameters) async { ... } } ``` -------------------------------- ### Simplified Mock Registration Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Use the simplified syntax for registering mocks directly without the `.register` keyword. This is a more concise way to set up test dependencies. ```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) } ``` -------------------------------- ### Tracing a Dependency Resolution Cycle Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Cycle.md Observe the step-by-step resolution of dependencies, including the creation of new instances and the reuse of cached ones. This trace helps visualize the order of operations and identify potential cycles. ```text 0: Container.cycleDemo = N:105553131389696 1: Container.aService = N:105553119821680 2: Container.implementsAB = N:105553119821680 3: Container.networkService = N:105553119770688 1: Container.bService = N:105553119821680 2: Container.implementsAB = C:105553119821680 ``` -------------------------------- ### Isolated Tests Using FactoryKit Container Trait Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md This example shows how to use the `.container` trait with `@Test` to ensure each test runs in its own isolated context with a unique container, preventing race conditions and random failures. ```swift import Testing import FactoryTesting struct AppTests { @Test(.container) func testA() async { Container.shared.someService{ ErrorService() } let service = Container.shared.someService() #expect(service.error == "Oops") } @Test(.container, arguments: Parameters.allCases) func testB(parameter: Parameters) async { Container.shared.someService { MockService(parameter: parameter) } let service = Container.shared.someService() #expect(service.parameter == parameter) } } ``` -------------------------------- ### FactoryKitDynamic Library Definition Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Modules.md Shows how to define the FactoryKitDynamic library product, which forces FactoryKit to be linked as a separate dynamic library. ```swift .library( name: "FactoryKitDynamic", type: .dynamic, targets: ["FactoryKit"] ), ``` -------------------------------- ### SwiftUI Preview with Mocked Service Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Previews.md This snippet shows how to register a mock service for a specific preview using the `Container.shared` instance. It's useful for setting up a particular state for a `ContentView`. ```swift struct ContentView_Previews: PreviewProvider { static var previews: some View { Container.shared.myService { MockServiceN(4) } ContentView() } } ``` -------------------------------- ### Environment-Specific Overrides with Contexts Source: https://github.com/hmlongco/factory/blob/main/CLAUDE.md Illustrates using contexts to provide environment-specific overrides for factories. These are useful for testing, debugging, or specific runtime conditions. ```swift container.analytics .onTest { MockAnalytics() } // DEBUG-only .onPreview { MockAnalytics() } // DEBUG-only .onDebug { MockAnalytics() } // DEBUG-only .onArg("mock1") { MockServiceN(1) } // available at runtime .onSimulator { ... } .onDevice { ... } ``` -------------------------------- ### Shortcut for Test Context Registration Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Contexts.md A convenient shortcut to register a dependency specifically for the test context, simplifying the code. ```swift container.analytics .onTest { MockAnalyticsEngine() } ``` -------------------------------- ### Constructor Injection with Dependencies Source: https://github.com/hmlongco/factory/blob/main/CLAUDE.md Illustrates constructor injection where a service depends on other services. The `network` service is registered as a singleton. ```swift extension Container { var repo: Factory { self { Repo(net: self.network()) } } var network: Factory { self { LiveNetwork() }.singleton } } ``` -------------------------------- ### Define Container KeyPaths for Processors Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Tags.md Create a static array of KeyPaths to all known processor factories in the container. ```swift extension Container { public static var processors: [KeyPath>] = [ \.processor1, \.processor2, ] } ``` -------------------------------- ### Auto-Registering Services in a Custom Container Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Containers.md Shows how to make a custom container conform to `AutoRegistering` to perform service registrations once before the first service resolution. ```swift extension MyContainer: AutoRegistering { func autoRegister() { someService { ModuleB.SomeService() } } } ``` -------------------------------- ### Formal Basic Dependency Registration Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Registrations.md An alternative, more formal way to register a basic dependency by explicitly constructing the Factory. ```swift extension Container { var service: Factory { Factory(self) { MyService() } } } ``` -------------------------------- ### Chaining Factory Definitions Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Modifiers.md Apply internal definitions, then override with 'onTest', and immediately resolve the service. ```swift let myService = Container.shared.myService .onTest { NullAnalyticsEngine() } .() ``` -------------------------------- ### Resolve a Service from Container Source: https://github.com/hmlongco/factory/blob/main/CLAUDE.md Demonstrates different ways to resolve a service from a container. Use the shared container or a specific container instance. ```swift let svc = Container.shared.myService() // service-locator style let svc = container.myService() // passed-container style class VM { @Injected(\.myService) var service // resolved at init } ``` -------------------------------- ### Test with Mocked Dependency Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Demonstrates how to register a mock, instantiate a dependent object, and then perform assertions. This pattern is common for testing view models or business logic. ```swift func testNoAccounts() async { // register a mock Container.shared.accountLoading.register { MockNoAccounts() } // instantiate the model that uses the mock let model = Container.shared.accountsViewModel() // and test... await model.load() XCTAssertTrue(model.isLoaded) XCTAssertTrue(model.isEmpty) } ``` -------------------------------- ### Define Factory with Syntactic Sugar Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Design.md Use this convenience syntax to define a factory within a container, simplifying the process of creating instances. ```swift extension Container { var myService: Factory { self { MyService() } } } ``` -------------------------------- ### Registering a Dependency for Multiple Launch Arguments Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Contexts.md Use .onArgs to register a single factory that will be used if any of the specified launch arguments are present. This simplifies handling multiple similar test scenarios. ```swift myServiceType .onArgs(["mock0", "mock1", "mock3"]) { EmptyService() } ``` -------------------------------- ### Import FactoryKit Source: https://github.com/hmlongco/factory/blob/main/README.md Import the FactoryKit library in your Swift files when using Factory. ```swift import FactoryKit ``` -------------------------------- ### Mocking Dependencies in Previews Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/GettingStarted.md Override a factory registration within a preview provider to inject mock dependencies. This allows for isolated testing of UI components without live API calls. ```swift struct ContentView_Previews: PreviewProvider { static var previews: some View { Container.shared.myService { MockService2() } ContentView() } } ``` -------------------------------- ### Registrations within Custom Containers Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Registrations.md Demonstrates creating factory registrations directly within a custom container class. Avoid 'lazy' factory definitions to prevent reference cycles. ```swift final class ServiceContainer: SharedContainer { // CONFORMANCE static var shared = ServiceContainer() var manager = ContainerManager() // DEFINE FACTORY var service1: Factory { self { MyService() } } // DON'T DO THIS lazy var service2: Factory = self { MyService() } } ``` -------------------------------- ### Passing Container to ViewModel Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Containers.md Initialize a ViewModel with a container instance and resolve services from it. ```swift class ContentViewModel { let service2: MyServiceType init(container: Container) { service2 = container.service() } } ``` -------------------------------- ### Optional or Promised Factories for External Implementations Source: https://github.com/hmlongco/factory/blob/main/CLAUDE.md Demonstrates how to declare optional or promised factories for modules where the implementation might be provided elsewhere. This is useful for modular architectures. ```swift extension Container { var accountLoader: Factory { promised() } } ``` -------------------------------- ### Handling Optional Dependencies with @Injected Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Modules.md Demonstrates how to safely inject an optional dependency using the @Injected property wrapper. This approach ensures the application does not crash if the dependency is not registered, by checking for its existence before use. ```swift class ViewModel: ObservableObject { @Injected(\.accountLoader) var loader @Published var accounts: [Account] = [] func load() { guard let loader else { return } accounts = loader.load() } } ``` -------------------------------- ### Instantiate Dependency from Shared Class Container Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Resolutions.md Use this pattern to instantiate a dependency from a shared class container, similar to the Service Locator pattern. ```swift class ContentViewModel: ObservableObject { let service = Container.shared.constructedService() } ``` -------------------------------- ### Resetting Factories and Scopes Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Additional/Migration.md Demonstrates how to reset factories and their scopes using the Container's manager. Options allow for selective resetting of registrations or scope caches. ```swift // Reset everything based in that container. Container.shared.manager.reset() // Reset all registrations, restoring original factories but leaving caches intact Container.shared.manager.reset(options: .registration) // Reset all scope caches, leaving registrations intact Container.shared.manager.reset(options: .scope) ``` ```swift Container.shared.manager.reset(scope: .cached) ``` -------------------------------- ### Demonstrating Container Release and Cache Reset Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Containers.md This snippet shows how creating a new container instance and assigning it to the existing variable releases the old container and its cache. Subsequent calls to cached services will yield new instances. ```swift 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) ``` -------------------------------- ### Basic Dependency Registration Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Registrations.md Register a basic dependency that returns a new instance each time. This is the preferred concise syntax. ```swift extension Container { var service: Factory { self { MyService() } } } ``` -------------------------------- ### Wire Factories Using AutoRegistering Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Modules.md Implement AutoRegistering in the application's Container to wire factories before any are resolved. This is where you provide the concrete implementation for factories defined in protocol modules. ```swift import ModuleP import ModuleA import ModuleB extension Container: AutoRegistering { func autoRegister { accountLoader.register { AccountLoader() } ... } } ``` -------------------------------- ### Using StateObject with Factory for View Models Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/SwiftUI.md Demonstrates how to define a Factory for a view model and use it with `@StateObject` in a SwiftUI View. Factory manages the construction and lifecycle of the view model. ```swift class ContentViewModel: ObservableObject { @Injected(\.myService) private var service @Published var results: Results func load() async { results = await service.load() } } extension Container { var contentViewModel: Factory { self { ContentViewModel() } } } struct ContentView: View { @StateObject var viewModel = Container.shared.contentViewModel() var body: some View { ... } } ``` -------------------------------- ### Constructor Injection with Dependencies Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Registrations.md Register a service that requires another service as a parameter during its construction. The dependency is obtained by asking the Factory for it. ```swift extension Container { var constructedService: Factory { self { MyConstructedService(service: self.cachedService()) } } var cachedService: Factory { self { MyService() }.cached } } ``` -------------------------------- ### Registering a Dependency for the Test Context Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Contexts.md Use the .test context to provide a specific dependency, like a MockAnalyticsEngine, when running unit tests. ```swift container.analytics .context(.test) { MockAnalyticsEngine() } ``` -------------------------------- ### Conditional Registration with `onArg` Context Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Simplify conditional registrations for testing by using the `onArg` context. This method achieves the same result as checking launch arguments directly but with a more concise syntax. ```swift import Foundation import Factory extension Container: AutoRegistering { public func autoRegister() { #if DEBUG myServiceType.onArg("mock1") { MockServiceN(1) } #endif } } ``` -------------------------------- ### Requesting a Factory Instance Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Cycle.md Initiates the dependency resolution process by asking a Factory to resolve and return an instance of a desired object. ```swift let demo = Container.shared.cycleDemo() ``` -------------------------------- ### Register a New Factory Closure (Shortcut) Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/GettingStarted.md A shorthand syntax for registering a new factory closure. This overrides the default factory closure and clears the associated scope. ```swift container.service { MockService() } ``` -------------------------------- ### Define a Protocol for Account Loading Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Modules.md Define a public protocol that outlines the contract for account loading functionality. This protocol serves as the abstraction layer for inter-module communication. ```swift public protocol AccountLoading { func load() -> [Account] } ``` -------------------------------- ### Classic Factory from Static Class Member (Deprecated) Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Resolutions.md Initialize a dependency from a class member. This is a classic Service Locator pattern and is considered deprecated. ```swift class ContentViewModel: ObservableObject { let newSchool = Container.newSchool() } ``` -------------------------------- ### Default Service Registration Source: https://github.com/hmlongco/factory/blob/main/README.md This snippet shows the default way to register a service with the container. It is used when no specific mock or alternative implementation is needed. ```swift extension Container { static var myService: MyServiceType { MyService() } } ``` -------------------------------- ### Importing FactoryTesting Module Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Shows the necessary import statement for the `FactoryTesting` module, which provides support for container traits in tests. ```swift import Testing import FactoryTesting ``` -------------------------------- ### Append a new processor factory Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Tags.md Dynamically add a new processor factory to the list of known processors by appending its KeyPath. ```swift extension Container: AutoRegistering { func autoRegister() { Container.processors.append(\.processor3) } var processor3: Factory { self { Processor3() } } } ``` -------------------------------- ### Set and Remove Runtime Arguments Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Contexts.md Demonstrates how to dynamically set and remove arguments that can influence factory contexts at runtime. These arguments can be used with `onArg` modifiers. ```swift FactoryContext.setArg("light", forKey: "theme") FactoryContext.removeArg(forKey: "theme") ``` -------------------------------- ### Conditional Registration for Test Environment Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Contexts.md Manually register a mock engine if the test environment is detected by checking the process info environment. This is an alternative to using the .test context. ```swift if ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil { container.analytics.register { MockAnalyticsEngine() } } ``` -------------------------------- ### Recommended Factory Registration Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Registrations.md The recommended approach for defining factories as computed variables within a Container, accessed via the shared instance. ```swift extension Container { var newSchool: Factory { self { School() } } } let school = Container.shared.newSchool ``` -------------------------------- ### Archive Common Scheme for iOS Simulator Source: https://github.com/hmlongco/factory/blob/main/FactoryDemo/Modules/xcarchive.txt Archives the 'Common' scheme for the iOS Simulator. Ensures the library is built 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 ``` -------------------------------- ### Registering a Factory with Modifiers Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Modifiers.md Define a factory registration with initial configuration and modifiers like singleton scope and test-specific overrides. ```swift extension Container { public func myService: Factory() { self { MyService() } .singleton .onTest { MockAnalyticsEngine() } } } ``` -------------------------------- ### Auto-Registering Services in the Default Container Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/Containers.md Demonstrates how to add auto-registration capabilities to Factory's default container using the `@retroactive` attribute, which is necessary in Swift 6 to avoid warnings. ```swift extension Container: @retroactive AutoRegistering { func autoRegister() { someService { ModuleB.SomeService() } } } ``` -------------------------------- ### Archive Networking Scheme for iOS Simulator Source: https://github.com/hmlongco/factory/blob/main/FactoryDemo/Modules/xcarchive.txt Archives the 'Networking' scheme for the iOS Simulator. Ensures the library is built 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 ``` -------------------------------- ### Custom Factory Registration with FatalError Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Modules.md Shows how to create a custom factory registration that calls fatalError if the dependency is accessed before being registered. This provides a 'fail fast' mechanism during development. ```swift extension Container { public var accountLoader: Factory { self { fatalError() } } } ``` -------------------------------- ### Using Promised Factories for Optional Dependencies Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Modules.md Demonstrates the use of the `promised()` function to register an optional dependency. In debug builds, it triggers a fatal error if unregistered; in release builds, it safely returns nil, preventing application crashes. ```swift extension Container { public var accountLoader: Factory { promised() } } ``` -------------------------------- ### Resolve all registered processors Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Tags.md Map the defined KeyPaths to their corresponding factories and resolve all processor instances. ```swift extension Container { public func processors() -> [Processor] { Container.processors.map { self[keyPath: $0]() } } } ``` -------------------------------- ### Unit Testing with Swift Testing Traits Source: https://github.com/hmlongco/factory/blob/main/README.md Demonstrates using Swift Testing traits to isolate container instances for each test. Ensures a fresh container for testing different states like loaded, empty, or error conditions. ```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") } } ``` -------------------------------- ### Passing Container to ViewModel for Dependency Injection Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Instantiate a container and pass it to your view model during initialization. This allows the view model to access and use services registered within that specific 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) } } ``` -------------------------------- ### Factory Registrations for Dependency Resolution Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Cycle.md Configures Factory instances for various types, including direct factories, factories that resolve other factories, and graph factories for complex dependencies. ```swift extension Container { var cycleDemo: Factory { self { CycleDemo() } } var aService: Factory { self { self.implementsAB() } } var bService: Factory { self { self.implementsAB() } } private var implementsAB: Factory { self { ImplementsAB() } .graph } var networkService: Factory { self { NetworkService() } } var preferences: Factory { self { Preferences() } } } ``` -------------------------------- ### Factory 1.x vs 2.0 Registration Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Additional/Migration.md Compares the syntax for registering a factory in FactoryKit 1.x (static variable) versus FactoryKit 2.0 (computed variable within a container). ```swift extension Container { // Factory 1.x static var service = Factory { MyService() } // Factory 2.0 var service: Factory { self { MyService() } } } ``` -------------------------------- ### Factory Scopes Source: https://github.com/hmlongco/factory/blob/main/CLAUDE.md Explains various scoping options for factories, controlling how instances are created and cached. Each scope has different lifecycle management. ```swift self { MyService() } // unique (default — new every call) self { MyService() }.cached // cached on the container self { MyService() }.shared // weakly cached on the container self { MyService() }.singleton // global, container-independent self { MyService() }.graph // cached for one resolution cycle self { MyService() }.scope(.session) // custom scope ``` -------------------------------- ### Register a Mock Dependency Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Development/Testing.md Register a mock implementation for a dependency to be used during testing. This is useful for isolating the code under test. ```swift Container.shared.accountLoading.register { MockNoAccounts() } ``` -------------------------------- ### Registering a Plain Actor Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Actors.md Define an actor and register it as a dependency using a Factory. The actor's initializer is nonisolated, allowing synchronous resolution. ```swift actor OrdinaryActor { private var count = 0 func increment() -> Int { count += 1 return count } } extension Container { var ordinaryActor: Factory { self { OrdinaryActor() } } } ``` -------------------------------- ### Define a Functional Factory for Account Providing Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Functional.md Register a factory that provides a closure for fetching accounts. The double braces indicate that the factory's closure returns another closure. ```swift typealias AccountProviding = () async throws -> [Account] extension Container { var accountProvider: Factory { self {{ try await Network.get(path: "/accounts")}} } } ``` -------------------------------- ### Formal Factory Definition Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Additional/Migration.md A complete definition of a Factory, explicitly specifying the container, scope, and the closure for creating an instance of the dependency. ```swift var service: Factory { Factory(self, scope: .unique) { MyService() } } ``` -------------------------------- ### Resolving Main Actor Factories Correctly Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Actors.md Shows the correct way to resolve a factory registered on the Main Actor from a background task using `resolveOnMainActor()`. ```swift Task.detached { let viewModel = await Container.shared.contentViewModel.resolveOnMainActor() await viewModel.load() } ``` -------------------------------- ### Aggregate processors from multiple modules Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Advanced/Tags.md Combine processor contributions from different modules by appending their respective available processors. ```swift extension Container: AutoRegistering { func autoRegister() { Container.processors += ModuleA.availableProcessors() Container.processors += ModuleB.availableProcessors() Container.processors += ModuleC.availableProcessors() } } ``` -------------------------------- ### Syntactic Sugar for Factory Creation Source: https://github.com/hmlongco/factory/blob/main/Sources/FactoryKit/FactoryKit.docc/Basics/GettingStarted.md Utilizes Factory's syntactic sugar with `callAsFunction` on `self` for a more concise factory definition. This is the preferred method for defining factories. ```swift var service: Factory { self { MyService() } } ```