Service Locator vs DI

The interviewer asks

“What's the difference between Service Locator and Dependency Injection?”

How to answer

Both decouple a type from the concrete implementations it uses; the difference is who does the looking up. With dependency injection a type declares what it needs in its init and something outside (a composition root, a coordinator, a parent view) passes it in, so dependencies are explicit, checked at compile time, and trivially replaced in tests. With a service locator the type reaches into a shared registry (ServiceLocator.shared.resolve(...)) at runtime, which hides the dependency, turns a missing registration into a runtime crash, and makes parallel tests share global state. I default to initializer injection; a locator, if used at all, belongs only at the composition root. SwiftUI's environment is a scoped, type-safe middle ground: @Environment looks up values, but the parent explicitly provides them for a subtree.

Key points

  • DI: init(api: any APIClient); dependencies visible in the signature
  • Locator: resolve(APIClient.self); dependencies hidden in the implementation
  • Locator failures are runtime (missing registration), DI failures are compile time
  • In Swift 6 a global registry is shared mutable state: it must be Sendable, so a Mutex or actor around the storage, and registered services must be Sendable
  • Swift Testing runs tests in parallel, so a global locator swapped per test causes flaky tests

If they dig deeper

  • When a locator is acceptable: legacy code you can't refactor yet, or plug-in systems where the set of services is truly dynamic. Even then, resolve once at the edge and inject from there
  • SwiftUI environment: @Entry var analytics: any Analytics = NoopAnalytics() plus .environment(\.analytics, live) is scoped and has a default, so it doesn't crash. @Environment(Model.self) for @Observable models traps if missing unless declared optional
  • DI containers: libraries such as Factory or Swinject are containers that can be used in either style; constructor injection through them is still DI

Common pitfalls

  • Calling it DI because there's a protocol, while every type calls a global resolve
  • A static var shared registry with a plain dictionary (a Swift 6 error, and a data race)
  • Resolving deep inside views or models, so tests have to configure a global
  • Force-unwrapping resolve results, so a missing registration crashes in production

How to use it

swift
import Synchronization

protocol APIClient: Sendable { func get(_ path: String) async throws -> Data }

// Dependency injection (preferred): explicit, compile-time checked
@MainActor
@Observable
final class FeedViewModel {
    private let api: any APIClient
    init(api: any APIClient) { self.api = api }
}

// Service locator: Swift 6-safe, but the dependency is hidden from callers
final class ServiceLocator: Sendable {
    static let shared = ServiceLocator()
    private let services = Mutex<[ObjectIdentifier: any Sendable]>([:])

    func register<T>(_ type: T.Type, _ service: any Sendable) {
        services.withLock { $0[ObjectIdentifier(type)] = service }
    }
    func resolve<T>(_ type: T.Type) -> T? {
        services.withLock { $0[ObjectIdentifier(type)] as? T }
    }
}

@MainActor
final class LegacyFeedViewModel {
    // Fails at runtime if nobody registered APIClient; tests must mutate a global
    private let api = ServiceLocator.shared.resolve((any APIClient).self)
}

// SwiftUI environment: scoped lookup with a safe default
struct NoopAPIClient: APIClient { func get(_ path: String) async throws -> Data { Data() } }
extension EnvironmentValues {
    @Entry var apiClient: any APIClient = NoopAPIClient()
}

Best practices

  • Inject through init; keep construction in one composition root
  • Use the SwiftUI environment for values many views need, with a safe default
  • Confine any locator to the app's edge and resolve once
  • Make registries Sendable (Mutex or actor) and services Sendable
  • Give each test its own instances instead of reconfiguring a global

Related concepts

  • Dependency injection, dependency graph, testing singletons, thread-safe singleton, protocol-oriented architecture, environment values