Factory for Dependency Injection in SwiftUI: A Complete Setup Guide

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

Development and support of all types of mobile applications:

Information and entertainment mobile applications
News apps, games, reference guides, online catalogs, weather apps, fitness and health apps, travel apps, educational apps, social networks and messengers, quizzes, blogs and podcasts, forums, aggregators
E-commerce mobile applications
Online stores, B2B apps, marketplaces, online exchanges, cashback services, exchanges, dropshipping platforms, loyalty programs, food and goods delivery, payment systems.
Business process management mobile applications
CRM systems, ERP systems, project management, sales team tools, financial management, production management, logistics and delivery management, HR management, data monitoring systems
Electronic services mobile applications
Classified ads platforms, online schools, online cinemas, electronic service platforms, cashback platforms, video hosting, thematic portals, online booking and scheduling platforms, online trading platforms

These are just some of the types of mobile applications we work with, and each of them may have its own specific features and functionality, tailored to the specific needs and goals of the client.

Showing 1 of 1All 1734 services
Factory for Dependency Injection in SwiftUI: A Complete Setup Guide
Medium
~2-3 days

Our competencies:

Frequently Asked Questions

Latest works

  • image_mobile-applications_feedme_467_0.webp
    Development of a mobile application for FEEDME
    895
  • image_mobile-applications_xoomer_471_0.webp
    Development of a mobile application for XOOMER
    782
  • image_mobile-applications_rhl_428_0.webp
    Development of a mobile application for RHL
    1216
  • image_mobile-applications_zippy_411_0.webp
    Development of a mobile application for ZIPPY
    1079
  • image_mobile-applications_affhome_429_0.webp
    Development of a mobile application for Affhome
    1002
  • image_mobile-applications_flavors_409_0.webp
    Development of a mobile application for the FLAVORS company
    597

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

  1. Add the Factory package via Swift Package Manager.
  2. Create an extension on Container and describe factories for all layers of the app.
  3. In Views, use @StateObject with a container factory.
  4. For services, use @Injected or @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 @Injected for 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

  1. Analysis: we review the code, identify existing connections and pain points.
  2. Design: we define module boundaries and choose scopes.
  3. Implementation: we create the Container and move initialization.
  4. Testing: we cover key scenarios with unit tests.
  5. 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