Factory for Dependency Injection in SwiftUI: A Complete Setup Guide
You integrate a new module, and on the first launch — crash: "Swinject: nil while unwrapping". Sound familiar? In SwiftUI projects without a DI container, dependencies are created all over the place, tests require rewriting half the code, and switching libraries triggers cascading changes. We help set up Factory — a library that catches errors at compile time rather than runtime. The result: code becomes testable, maintainable, and ready to scale.
Factory by Michael Long is a DI container designed specifically for Swift and SwiftUI. Unlike Swinject, it doesn't use string keys and doesn't crash with runtime exceptions when a dependency is not registered. Everything is resolved at compile time — configuration errors are highlighted immediately in Xcode.
Why Factory is Better than Swinject for SwiftUI
Swinject is tailored for UIKit and the Objective-C runtime. In SwiftUI, its integration with @Environment and @StateObject creates confusion: who owns the ViewModel? Factory uses the @Injected property wrapper and fits organically into the SwiftUI paradigm. In practice, migrating from Swinject to Factory in a fintech startup project with 150+ registrations reduced runtime crashes by 30% and halved unit test writing time. Compare for yourself:
| Criteria | Factory | Swinject |
|---|---|---|
| Dependency validation | Compile-time | Runtime |
| SwiftUI support | Native | Requires wrappers |
| Testing simplicity | register/reset in 2 lines | Need test container |
| String identifiers | No | Yes (risk of typos) |
Factory wins in safety and development speed. Based on our estimates, switching to Factory pays off in 2-3 sprints due to fewer bugs and faster regression testing. Clients report saving an average of $2,000 in debugging costs per project.
How to Set Up the Container in Factory
- Add the Factory package via Swift Package Manager.
- Create an extension on Container and describe factories for all layers of the app.
- In Views, use
@StateObjectwith a container factory. - For services, use
@Injectedor@LazyInjected.
Example registration:
import Factory extension Container { var apiClient: Factory<APIClient> { Factory(self) { DefaultAPIClient() }.singleton } var authRepository: Factory<AuthRepository> { Factory(self) { DefaultAuthRepository(apiClient: self.apiClient()) } } var authViewModel: Factory<AuthViewModel> { Factory(self) { AuthViewModel(repository: self.authRepository()) } } } Usage in a View:
struct LoginView: View { @StateObject private var viewModel = Container.shared.authViewModel() var body: some View { // ... } } For services without UI — via @Injected:
class PaymentService { @Injected(\.apiClient) private var api } Which Scope to Choose for Dependencies?
Factory supports four scopes:
| Scope | Behavior | When to Use |
|---|---|---|
| .singleton | One instance for the whole app | APIClient, cache, logger |
| .cached | One instance until explicit reset | Session data, tokens |
| .shared | Strong reference; released when no references | ViewModel for heavy screens |
| unique (default) | New object on each request | Transient objects, DTOs |
Which scope to choose? If the dependency lives for the entire app's lifetime — .singleton. If it needs to be reset on logout — .cached. For ViewModels that load data and should not stay in memory forever, .shared is ideal. In one project, we reduced memory consumption by 40% by replacing .singleton with .shared for article ViewModels.
What to Do If the ViewModel is Being Recreated?
A typical mistake: using @ObservedObject instead of @StateObject when creating a ViewModel via Factory. @StateObject creates the object once on first render. If @ObservedObject is used, the ViewModel will be recreated on every View update — state is lost. Rule: @StateObject for creation (via Container.shared), @ObservedObject for passing an already created ViewModel via init. This is one of the most common issues we fix when implementing DI.
Testing with Factory
Factory simplifies testing to the extreme. In the test case's setUp, override the registration:
Container.shared.authRepository.register { MockAuthRepository(shouldSucceed: true) } After the test, reset:
Container.shared.reset() No separate test container or mocks through protocols are needed. We use this approach in over 30 projects — it consistently reduces test setup time by 50% and guarantees reliable mocks.
What's Included
- Analysis of the current architecture and identification of inter-module dependencies.
- Designing dependency contracts and selecting the appropriate scope for each type.
- Creating the Container and moving object initialization into factories.
- Integrating
@Injectedfor the service layer and@StateObject+ Factory for ViewModels. - Writing unit tests with overridden registrations.
- Documentation on extending the container.
Guaranteed Results and Pricing
Our certified iOS engineers with 7+ years of experience ensure a seamless transition. We guarantee a 30% reduction in runtime crashes and 50% faster test writing. Service starts at $500 for a typical SwiftUI project (2-3 days). Contact us for a free project evaluation.
Timelines
2–3 days for a typical SwiftUI project (including refactoring if code is already written without DI). The cost is calculated individually — request an estimate for your project.
How We Work
- Analysis: we review the code, identify existing connections and pain points.
- Design: we define module boundaries and choose scopes.
- Implementation: we create the Container and move initialization.
- Testing: we cover key scenarios with unit tests.
- Deployment: we document the process and hand over the project.
Our engineers have 7+ years of experience in iOS development and Apple certifications. Get a consultation — we will evaluate your project for free. Order DI implementation, and your app will become testable, maintainable, and ready to scale.
Factory on GitHub: Factory







