Dependency injection and the AppContext
One AppContext builds every dependency and hands it down. Modules never construct their own, so any piece can be swapped, faked, or tested.
This is the note where all the Lego pieces get snapped together.
The idea behind dependency injection is simple: a piece of code never builds its own dependencies. It receives them. A setlist builder doesn’t create a storage client. It’s handed something that satisfies the SongStorage interface, and it uses that. It has no idea whether that’s S3, a folder on disk, or a dictionary in a test.
In my programs, the thing doing the handing is a single AppContext. main creates it, the AppContext builds every real implementation and manages their lifecycles, and everything else gets what it needs from there.
What it looks like without it
# setlists/build.py
import os
from gigbook.storage import S3SongStorage
_storage = S3SongStorage(bucket_name=os.environ["GIGBOOK_SONG_BUCKET_NAME"])
def build_setlist(name: str, song_ids: Sequence[SongId]) -> Setlist:
return Setlist(name=name, songs=tuple(_storage.load_song(song_id) for song_id in song_ids))
It looks harmless, but this module has quietly decided four things that aren’t its business: which storage implementation to use, where its settings come from, that there’s exactly one storage instance, and that it gets created the moment anyone imports the module. Now you can’t test build_setlist without real S3 credentials. You can’t use a different storage for one command. Just importing the module connects to AWS. And if three modules each do this, there are three storage clients and three places reading the environment.
The AppContext
Here’s gigbook’s whole AppContext. It’s just a frozen dataclass whose fields are interfaces, plus one function that builds the real implementations:
from collections.abc import Iterator
from contextlib import closing, contextmanager
from dataclasses import dataclass
from gigbook.chord_charts import ChordChartService, HttpChordChartService
from gigbook.config import Config
from gigbook.storage import S3SongStorage, SongStorage
@dataclass(frozen=True)
class AppContext:
"""What every module may depend on. Each field is an interface, never an implementation."""
chord_chart_service: ChordChartService
config: Config
song_storage: SongStorage
@contextmanager
def open_app_context(config: Config) -> Iterator[AppContext]:
"""Builds the real implementations, and closes whatever needs closing when the app is done."""
with closing(HttpChordChartService(base_url=config.chord_chart_api_url)) as chord_chart_service:
yield AppContext(
chord_chart_service=chord_chart_service,
config=config,
song_storage=S3SongStorage(bucket_name=config.song_bucket_name),
)
(If @contextmanager and closing are new to you: together they mean “build these things, hand them out for the duration of a with block, and clean them up when the block ends, even if something fails.” That’s the AppContext managing lifecycles: the HTTP connection pool is opened once and closed once, and no other code has to remember to do it.)
This is the only file that names concrete classes like S3SongStorage. Everything else in the program depends on SongStorage, the interface.
Walking through from main
The app’s flow should be easy to follow starting from main, and with an AppContext it really is:
from gigbook.app_context import open_app_context
from gigbook.config import EnvironmentConfig
from gigbook.nouns import SongId
from gigbook.setlists import build_setlist, describe_setlist
FRIDAY_SONG_IDS = [SongId("the-thrill-is-gone"), SongId("pride-and-joy"), SongId("little-wing")]
def main() -> None:
config = EnvironmentConfig()
with open_app_context(config) as app_context:
setlist = build_setlist(app_context, "Friday at the Blue Room", FRIDAY_SONG_IDS)
print(describe_setlist(setlist))
Read the settings (and fail right away if any are missing). Build everything. Do the work. Clean up. There’s nothing hidden. And the feature itself just uses what it’s given:
def build_setlist(app_context: AppContext, name: str, song_ids: Sequence[SongId]) -> Setlist:
songs = tuple(app_context.song_storage.load_song(song_id) for song_id in song_ids)
return Setlist(name=name, songs=songs)
Testing becomes easy
Because nothing builds its own dependencies, a test builds an AppContext out of fakes. No mocking library tricks, no patching imports, no network:
class InMemorySongStorage:
"""A SongStorage that keeps songs in a dictionary, for tests."""
def __init__(self, songs: Iterable[Song]) -> None:
self._songs_by_id = {song.song_id: song for song in songs}
def load_song(self, song_id: SongId) -> Song:
if song_id not in self._songs_by_id:
raise SongNotFoundError(song_id)
return self._songs_by_id[song_id]
def save_song(self, song: Song) -> None:
self._songs_by_id[song.song_id] = song
def create_test_app_context(songs: Iterable[Song]) -> AppContext:
return AppContext(
chord_chart_service=UnusedChordChartService(),
config=FixedConfig(),
song_storage=InMemorySongStorage(songs),
)
def test_a_missing_song_stops_the_setlist() -> None:
with pytest.raises(SongNotFoundError):
build_setlist(create_test_app_context([]), "Friday", [SongId("not-a-song")])
(UnusedChordChartService and FixedConfig are two more fakes, a few lines each.)
The test checks behavior (a missing song stops the setlist), not implementation. It doesn’t care how many times storage was called or in what order. So the implementation can change freely, and the test only fails if the behavior actually changes. The type checker also confirms the fakes really satisfy the interfaces, so a fake can’t drift out of sync with the real thing.
Swapping a real piece works the same way. An offline mode is a different SongStorage in open_app_context. A staging environment is a different Config. One place changes; nothing else notices.
Singletons are the AppContext’s call, not the object’s
One thing I feel strongly about: an object should never decide for itself that only one of it exists. The classic self-made singleton looks like this:
class SongStorage:
_instance: "SongStorage | None" = None
@classmethod
def instance(cls) -> "SongStorage":
if cls._instance is None:
cls._instance = cls()
return cls._instance
Now every caller has to know it’s a singleton (SongStorage.instance(), not SongStorage()), which is a leak. It’s global state, so tests share it and leak into each other. And you can never have two, even when you need to, like copying songs from one storage to another.
How many instances exist (one for the whole app, a pool, one per request) is a lifecycle decision, and lifecycle belongs to the AppContext. The AppContext makes one and passes it down. If that ever changes, it changes in the AppContext, and the object and its users never know. The only thing allowed to be global is the AppContext itself, and gigbook doesn’t even need that: main creates it and passes it down.
(The one exception I make: when a language already has a well-established idiom, I follow it. Python’s logging.getLogger(__name__) is a good example. Everyone knows it, every library uses it, and fighting it would just make the code stranger.)
Where this leads
Put the notes together and this is what you get: a program built from Nouns, split into cohesive modules with no surprises behind their interfaces, with every vendor wrapped, boundaries the build enforces, and one AppContext snapping it all together. Every piece can be understood alone, tested alone, and replaced alone.
That’s the Lego set. It’s not more work than the soldered board. It’s the same work, done in an order that keeps paying you back.