The Best API Change Is the One Nobody Notices
Scene-aware custom containers in Factory, and the design that let the existing API stay put…
Every library author eventually learns that new capability costs new API.
A new feature means a new parameter, a new generic, a new protocol requirement, and a migration guide for everyone who already depends on you. It’s practically a law of nature.
Sometimes.
In my last article I introduced scene-based injection for Factory’s default container. It left a gap, and closing that gap looked like it was going to break things. It didn’t, and the reason why is worth a look.
The Gap
Here’s what scenes gave us. Install a Container at the root of each window, publish it in the environment, and @InjectedObject and @InjectedObservable resolve from it instead of Container.shared.
@main
struct DemoApp: App {
var body: some Scene {
WindowGroup {
SceneRoot()
}
}
}
struct SceneRoot: View {
@State private var sceneContainer = Container()
var body: some View {
ContentView()
.withContainer(sceneContainer)
}
}
struct ContentView: View {
@InjectedObservable(.contentViewModel) var model
var body: some View {
Text(model.text)
}
}
@main
struct DemoApp: App {
var body: some Scene {
WindowGroup {
SceneRoot()
}
}
}
struct SceneRoot: View {
@State private var sceneContainer = Container()
var body: some View {
ContentView()
.withContainer(sceneContainer)
}
}
struct ContentView: View {
@InjectedObservable(.contentViewModel) var model
var body: some View {
Text(model.text)
}
}
But Factory has always let you define your own containers. And when you pointed a wrapper at one, this is what it did under the hood.
<button data-code="public init(_ keyPath: KeyPath<C, Factory>) {
self._dependency = .init(wrappedValue: ThunkedValue(thunkedValue: { _ in C.shared[keyPath: keyPath]() }))
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-1/2 -translate-y-1/2 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
public init<C: SharedContainer>(_ keyPath: KeyPath<C, Factory<T>>) {
self._dependency = .init(wrappedValue: ThunkedValue(thunkedValue: { _ in C.shared[keyPath: keyPath]() }))
}
public init<C: SharedContainer>(_ keyPath: KeyPath<C, Factory<T>>) {
self._dependency = .init(wrappedValue: ThunkedValue(thunkedValue: { _ in C.shared[keyPath: keyPath]() }))
}
See the C.shared? That’s a global. Which is exactly the thing we spent the last article getting rid of.
So @InjectedObservable(MyContainer.service) ignored the scene entirely. Two windows, one MyContainer, and the same bug all over again.
The Obvious Answer
The cheap fix is a withContainer overload that takes a container type and registers on C.shared.
.withContainer(MyContainer.self) {
$0.service.register { MockService() }
}
.withContainer(MyContainer.self) {
$0.service.register { MockService() }
}
And it works. For previews, it’s fine. Register a mock, render the view, done.
But it’s not per scene. It just mutates the global with a nicer syntax, and that isn’t the problem I was trying to solve.
The Next Obvious Answer
So I needed to make the environment type-aware. My solution was to define a generic key, one per container type, and let each scene install its own.
<button data-code="struct SceneContainerKey: EnvironmentKey { … }” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-1/2 -translate-y-1/2 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
struct SceneContainerKey<C: SharedContainer>: EnvironmentKey { ... }
struct SceneContainerKey<C: SharedContainer>: EnvironmentKey { ... }
Sounds right, right?
Well, not really. The wrappers are generic over the dependency, not the container. InjectedObject<T> has no idea what C is until you hand it a key path, and by then the struct’s stored properties are already fixed.
To read a key for an arbitrary C from inside the wrapper, you’d need @Environment(.self), which as far as I can tell invalidates the view whenever anything in the environment changes. Not good.
Or you could add C as a second generic parameter, and InjectedObject<T, C> breaks every declaration in every app that uses it.
Also not good. That’s exactly the kind of API change I was trying to avoid.
One Key, Many Containers
Here’s the thing about generics. When the variation is in the type, you pay for it in the signature. When the variation is in data, you don’t.
So the solution is to move the variation out of the type system and into data.
One environment value. One fixed key. Inside it, a dictionary of every scene container that’s been installed, keyed by the container’s type.
<button data-code="struct SceneContainers: Equatable, Sendable {
private var containers: [ObjectIdentifier: any SharedContainer] = [:]
subscript(_ type: C.Type) -> C {
get { (containers[ObjectIdentifier(type)] as? C) ?? C.shared }
set { containers[ObjectIdentifier(type)] = newValue }
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
struct SceneContainers: Equatable, Sendable {
private var containers: [ObjectIdentifier: any SharedContainer] = [:]
subscript<C: SharedContainer>(_ type: C.Type) -> C {
get { (containers[ObjectIdentifier(type)] as? C) ?? C.shared }
set { containers[ObjectIdentifier(type)] = newValue }
}
}
struct SceneContainers: Equatable, Sendable {
private var containers: [ObjectIdentifier: any SharedContainer] = [:]
subscript<C: SharedContainer>(_ type: C.Type) -> C {
get { (containers[ObjectIdentifier(type)] as? C) ?? C.shared }
set { containers[ObjectIdentifier(type)] = newValue }
}
}
Ask for a container type that was installed and you get the scene’s instance. Ask for one that wasn’t and you get C.shared, which is exactly what you got yesterday.
That fallback is the entire compatibility story. A view that never installs anything behaves the way it always did.
It’s also Equatable, comparing the stored containers by identity. Re-publishing the same containers shouldn’t wake up every view downstream, and now it doesn’t.
The Old Key Path
Now for the part I like best. Remember .container, the public environment key path we shipped for the default container? People are already using it.
It’s still there. It’s just not a stored entry anymore.
public var container: Container {
get { sceneContainers[Container.self] }
set { sceneContainers[Container.self] = newValue }
}
public var container: Container {
get { sceneContainers[Container.self] }
set { sceneContainers[Container.self] = newValue }
}
A computed property over the new registry. .environment(.container, sceneContainer) still compiles, @Environment(.container) still compiles, and nobody has to touch a line.
And Container stopped being a special case. It’s now just one more entry in the dictionary.
Bingo.
The Wrappers
So what happened to the wrappers? Almost nothing, and what changed isn’t public.
Each one used to read @Environment(.container). Now each one reads @Environment(.sceneContainers), the fixed key, and the closure that resolves the dependency asks the registry for the right container by type.
// The default Container
{ $0[Container.self][keyPath: keyPath]() }
// A custom container
{ $0[C.self][keyPath: keyPath]() }
// The default Container
{ $0[Container.self][keyPath: keyPath]() }
// A custom container
{ $0[C.self][keyPath: keyPath]() }
Same public initializers, same generic parameters, and the same behavior if you never install anything. The only visible difference is that MyContainer.service now finds the scene’s MyContainer instead of MyContainer.shared.
Which was the entire point.
What Actually Grew
Something has to be new, of course. Here’s what it cost.
.withContainer(MyContainer.self) { $0.service.register { MockService() } }
.withContainer(MyContainer.service) { MockService() }
.withContainer(sceneContainer)
.withContainer(MyContainer.self) { $0.service.register { MockService() } }
.withContainer(MyContainer.service) { MockService() }
.withContainer(sceneContainer)
Three overloads of a modifier that already existed. The first two mirror the closure and key path forms that Container already had, just generic over the container type.
The third is the one that makes this work at all. Without a way to install a custom container for a scene, nothing is scene-specific. .environment(.container, c) only ever reached Container.
I did worry about the key path form. The demo already uses the implicit version, .withContainer(.id), and I was afraid adding a generic sibling would make the compiler throw up its hands. It doesn’t.
The implicit form still resolves to the default container, and there’s a test to prove it.
And the placement rule hasn’t changed. Register inside the view that installs the container, or you’re registering on the shared one.
Reading It Back
One more problem. Once a custom container lives in the environment, how does a view get hold of it?
Factory already has @InjectedContainer, but it was built for classes. It grabs C.shared at initialization, and a view’s environment doesn’t exist yet at initialization.
So I made it a DynamicProperty. But there’s a catch, and it’s a nasty one.
Read @Environment anywhere outside of a view, say from a view model that also uses @InjectedContainer, and SwiftUI logs a warning. The wrapper has to work in both places without complaining.
Well, SwiftUI only calls update() when the wrapper is actually installed in a view. So that’s where it takes its copy.
extension InjectedContainer: DynamicProperty {
public mutating func update() {
scene.containers = sceneContainers
}
}
extension InjectedContainer: DynamicProperty {
public mutating func update() {
scene.containers = sceneContainers
}
}
The getter reads that copy, not the environment. In a view you get the scene container. In a class, update() never runs, so you get exactly what you always got, with no warnings.
It’s also read-only now. Installing a container belongs to withContainer. The wrapper just reads.
The Fine Print
There is one behavioral change, and I’d rather tell you than have you find it. An @InjectedContainer in a view used to give you the shared container. Now it gives you the scene’s, if there is one.
I think that’s what anyone using it in a view wanted. But it’s observable, so there it is.
The usual limits haven’t moved. @Injected, @LazyInjected, @WeakLazyInjected, @DynamicInjected, and a bare Container.shared.service() can’t see the environment. And reading the container in a view’s init quietly gets you the shared one.
Then there’s the question I’d ask myself. Keying a dictionary off ObjectIdentifier(C.self) means type identity matters. If the same module is statically linked into more than one binary in the same process, each copy gets its own metadata, and MyContainer in one wouldn’t match MyContainer in the other.
As far as I can tell that’s not a new weakness. A duplicated Factory would already have a duplicated Container.shared, and the registry’s own environment key would be duplicated with it.
But I haven’t built that configuration to prove it. And when it does go wrong, it fails by falling back to the shared container, which is quiet.
Completion Block
None of this was clever.
The interesting decision wasn’t what to write, it was where to put the changes. In the type system, it would have cost a signature change for everyone. In a dictionary, it cost three new modifiers and a computed property.
So what do you think? Have you got an app with more than one window, and a container type of your own? Did I miss a place where it breaks?
Drop me a line. And as always, stay tuned.
Custom scene containers are in Factory 3.5.1. The documentation has the full write-up, and the code is on GitHub.


