At a glance
- Problems
- More business-logic services meant more dependencies to manage.
- Direct service access increased coupling and made test substitution harder.
- Initialising and tearing down the service graph needed a controlled path.
- Constraints
- No additional DI package.
- Swift lacked the runtime reflection needed for the C#-style attribute-and-type lookup; KeyPaths provided typed service paths.
- Design goal
- KeyPath autocomplete surfaced available service paths at the injection site; developers did not need to memorise service types, property names, or string keys.
- The compiler checked the selected path, making changes easier to catch during builds and helping developers new to the codebase.
- Keep registrations extensible and make teardown and rebuilding explicit.
Context and goal
The luca iOS app had many services used across view models, coordinators, app startup, and other components. The goal was a small, predictable API for adding and consuming them, including for developers who did not yet know the project well. The constraints were to avoid another package dependency, keep service access checked by the Swift compiler, and avoid making every consumer reach into a global service bag.
In C#, a DI container can use richer runtime reflection to discover a marked property and resolve its type from registered services. Swift did not offer an equivalent reflection mechanism for this pattern when the system was built. Explicit, typed service paths supplied the lookup mechanism.
Approach
An in-house DependencyInjection module combines DependencyContext, provider types, and property wrappers. For the main path, each service has a typed provider slot declared in an extension of DependencyContext. A consumer writes an @InjectStatic property with a Swift KeyPath to that slot. The KeyPath and provider’s associated value type are checked together at compile time, so a registration and a consumer must agree on the service type. New slots can be added through extensions as the app grows; they are not a closed list baked into the injection wrapper.
Usage
A class declares the service it needs through a typed KeyPath. The property is resolved when first accessed:
import DependencyInjection
class NewCoolService {
@InjectStatic(\.userAccount) var userAccount
}
The corresponding binding is set up in a service initialiser. This short example assumes a userAccount provider slot and a constructed accountService:
try register(accountService)
.as(\.userAccount) { SharedProvider(value: $0) }
The registration contract also records how to remove that binding during invalidation.
How it works internally
These three paths show the registration, replacement, and teardown separately:
flowchart TB Initialiser[Service initialiser] --> Contract[Registration contract] --> Slot[Typed KeyPath slot] Consumer[Class with InjectStatic] --> Wrapper[Wrapper stores KeyPath] -->|First access| Slot Slot --> Provider[Shared or factory provider] --> Service[Service instance] --> Cache[Wrapper caches the value]
flowchart TB Replace[Replace provider] --> Setter[DependencyContext setter] Setter --> Swap[Disconnect old and connect new provider] Setter --> Signal[Removal and set notifications] --> Clear[Matching wrapper clears cache] Swap --> Next[Next access resolves replacement] Clear --> Next
flowchart TB Reset[Data reset] --> Disable[Disable services] --> Invalidate[Invalidate app initialiser] Invalidate --> Children[Invalidate child initialisers in reverse order] Children --> Contracts[Undo registration contracts] Contracts --> Empty[Restore empty typed providers and remove dynamic keys] Empty --> Reinitialise[Initialise services again]
A typed DependencyContext slot holds a provider, not the service itself. The context’s KeyPath subscript reads or replaces that provider; the provider’s associated type ties the slot to the value it can supply. There are providers for a shared instance, a factory that creates instances, and an empty slot after invalidation. @InjectStatic stores the KeyPath, asks the provider for a value on first access, and caches that value for the property.
Replacing a provider does more than assign a new value. The context sends removal and set notifications; wrappers watching the matching KeyPath clear their caches and resolve the new provider on the next access. Shared providers also have connection callbacks, guarded by a reference count so an instance registered through multiple bindings is disconnected only after its last binding is removed. Registration contracts keep the corresponding undo actions: invalidation restores an empty typed provider or removes a dynamic registration. The app-level initialiser then unwinds its child initialisers in reverse order.
The production service path uses typed KeyPaths. I also explored @InjectDynamic and @InjectAllDynamic for registrations addressed by type-derived or explicit keys, including collections of interface implementations. That experimental path resolves some keys at runtime and offers different guarantees from the typed KeyPath path.
Registration and lifecycle
As the number of services grew, service initialisers and registration contracts organized their setup. An initialiser registers a value or factory and binds it to one or more typed service paths or, where needed, dynamic keys. This kept registration in one place and gave the app a deliberate way to tear down and rebuild the service graph.
A shortened, independently recreated example follows the pattern of LucaIDInitialiser. One service can have more than one binding, and each as(...) call adds an undo action to the contract returned by register(...):
class IdentityServicesInitialiser: BaseServiceInitialiser, ImmediateServiceInitialiser {
func initialise() throws {
try register(IdentityKeys())
.as(\.identityKeys) { SharedProvider(value: $0) }
try register(IdentityService())
.as(\.identityService) { SharedProvider(value: $0) }
try register(IdentityProcessFetcher())
.as("identity-process-toggleable") { SharedProvider(value: $0 as Toggleable) }
.as(\.identityProcessFetcher) { SharedProvider(value: $0) }
}
}
The base initialiser retains the contracts and later invalidates them, so this class needs no matching cleanup method for each registration. The ordering is specific: the app initialiser invalidates its child initialisers in reverse order, while each BaseServiceInitialiser invalidates its own contracts in registration order.
The app’s data-reset flow uses that lifecycle: it disables services, invalidates their registrations, removes user data and databases, then reinitialises services. This is a concrete use of controlled teardown and rebuild. It also means a service consumer is coupled to its declared dependency rather than to direct access such as ServiceBag.shared.someService. The registry itself remains central inside the DI infrastructure.
Development began in 2021; registration and lifecycle evolved with the app.