Skip to content

Dependency injection and composition roots

Difficulty: Intermediate

Key concepts

  • composition root
  • object graph
  • ownership graph
  • constructor injection
  • member initialization order
  • service locator
  • hidden dependency
  • wiring test
  • What a composition root is: the one place, next to main, that creates the program’s objects and connects them.
  • How to draw an ownership graph, and the one rule it must obey: every non-owning reference points at an object that is destroyed later.
  • How a class that owns the whole graph uses member declaration order to fix the order of construction and destruction, and why such a class must refuse copying.
  • How to choose an adapter at run time from configuration, with a factory that returns a std::unique_ptr.
  • How wiring tests check the real graph, and how each test is its own composition root.
  • Why a service locator or a global hides a dependency, and how to find hidden dependencies in existing code.

The hexagonal program’s main built five objects as local variables, in an order chosen with care, and ran the script. That is a composition root, and for that program it is enough. Three ordinary requirements make it grow:

  1. Configuration. The registrar wants a rehearsal mode that runs commands without sending any notifications. The notifier is now chosen when the program starts, not when it is compiled.
  2. Tests of the wiring. Each unit test builds a small part of the graph. Nothing checks that main connected the real parts correctly, and main cannot be called from a test.
  3. Lifetime. Every object refers to others. As the graph grows, a wrong order of declarations becomes easy to write and hard to see.

The core and every adapter stay exactly as they were. The example for this page links the hexagonal example’s libraries unchanged; only the code that chooses, builds, and owns objects is new. That is the point of a composition root: when the wiring changes, nothing else does.

  • The object graph is the set of objects a program creates and the references between them: the service refers to the stores and the notifier, the console refers to the service.
  • The composition root is the single place where that graph is built. It is as close to the program’s entry point as possible, and it is the only code that names concrete adapter classes together.
  • The ownership graph is the same objects with each edge marked as owns (destroys it) or refers to (uses it, does not destroy it). Every object has exactly one owner, or is owned by the C++ runtime, like std::cout.

Step 1: classify each object by owner and lifetime

Section titled “Step 1: classify each object by owner and lifetime”

Before writing the root, list every object, who should own it, how others receive it, and why. The hexagonal classes take their collaborators as references in their constructors and store them as non-owning pointers, so that the pointer can never be reseated by accident and the class stays assignable:

Object Owner Others receive it as Why
Config main, a local value copied into nothing; read once Plain data read before anything is built.
the script main, a constant array — Input, not part of the graph.
MemoryCourses, MemoryStudents App, value members CourseStore&, StudentRegister& by the service Their types are fixed when compiling, so a value member is simplest.
the notifier object App, through a std::unique_ptr Notifier& by the service Its type is chosen at run time, so it must live on the heap behind its interface.
EnrollmentService App, a value member EnrollmentUseCases& by the console Exactly one, for the whole run.
Console App, a value member used only through App::run The driving adapter: the entry point for every command.
App main, a local variable — Lives for the whole run; destroyed at the end of main.
std::cout the C++ runtime std::ostream& by App’s constructor and the stream notifier Outlives main, so anything may refer to it.

Each row answers three questions: who creates it, who destroys it, and whether anyone can refer to it after it is destroyed. The last question is answered by the graph.

The ownership graph of the composition-root example: solid arrows own, dashed arrows only refer; every dashed arrow points at an object that is destroyed after the object it starts from
Text description of the diagram

An ownership graph. main owns App. The C++ runtime owns std::cout. Inside App, declared in this order, are five members that App owns: courses_, a MemoryCourses; students_, a MemoryStudents; notifier_, a unique_ptr to a Notifier; service_, an EnrollmentService; and console_, a Console. notifier_ in turn owns the notifier object on the heap, a StreamNotifier or a SilentNotifier. Non-owning references: service_ refers to courses_, students_, and the notifier object; console_ refers to service_; and a StreamNotifier refers to std::cout. Every reference points at something owned by a member declared earlier in App, or at std::cout, which outlives main, so each target is destroyed after whatever refers to it.

Diagram source (Mermaid)
flowchart TB
Main["main"]
Rt["C++ runtime"]
subgraph AppBox["App, owned by main"]
  Courses["courses_<br/>MemoryCourses"]
  Students["students_<br/>MemoryStudents"]
  Ptr["notifier_<br/>unique_ptr to Notifier"]
  Service["service_<br/>EnrollmentService"]
  Console["console_<br/>Console"]
end
Heap["the notifier object, on the heap<br/>StreamNotifier or SilentNotifier"]
Out["std::cout"]
Main -->|owns| AppBox
Ptr -->|owns| Heap
Rt -->|owns| Out
Service -.->|refers to| Courses
Service -.->|refers to| Students
Service -.->|refers to| Heap
Console -.->|refers to| Service
Heap -.->|"refers to (StreamNotifier only)"| Out

The rule to check on any ownership graph: every dashed arrow must point at something destroyed later than the object it starts from. Inside one owner, C++ makes that easy to arrange, as the next section shows. Ownership graphs and lifetime design applies the same rule to objects that are created and deleted while the program runs.

The App class: one owner for the whole graph

Section titled “The App class: one owner for the whole graph”

App is the composition root as a class. Its members are the graph:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

app.hpp
// The object graph of one run of the program, owned in one place.
// Members are declared in the order they must be built: everything a
// member refers to is declared above it. C++ destroys members in the
// reverse order, so nothing is destroyed while something still refers
// to it.
class App {
public:
// `out` receives notifications and must outlive the App. `config` is
// only read while the constructor runs (to choose the notifier), so it
// may be destroyed afterwards. Building an App builds the whole graph.
App(const Config& config, std::ostream& out);
// The members point at each other. The unique_ptr already blocks
// copying; these lines also suppress the implicit move, which would
// compile and leave the new App's service pointing at the old App's
// stores.
App(const App&) = delete;
App& operator=(const App&) = delete;
// Runs one console command and returns the reply. The App adds nothing
// of its own: it forwards the line to the console, the driving adapter.
std::string run(std::string_view line) { return console_.run(line); }
private:
// The App owns all five parts by value, except the notifier, which it
// owns through a std::unique_ptr because its class is chosen at run
// time (a StreamNotifier or a SilentNotifier). The two stores are the
// driven adapters for storage; nothing else owns them.
adapters::MemoryCourses courses_;
adapters::MemoryStudents students_;
// A unique_ptr to the port type, core::Notifier: the App knows it owns
// "some notifier", and deleting it through the base class is safe
// because Notifier has a virtual destructor.
std::unique_ptr<core::Notifier> notifier_; // owned, never null; chosen at run time
core::EnrollmentService service_; // refers to the three above
adapters::Console console_; // refers to service_
};

Two C++ rules do the work:

  • Members are constructed in the order they are declared, whatever order the constructor’s initializer list is written in.
  • Members are destroyed in the reverse order. The console goes first, then the service, then the notifier, then the stores.

So if every member refers only to members declared above it, nothing is ever used before it exists or after it is gone. The ownership graph’s rule becomes a rule about the order of lines in app.hpp.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

app.cpp
// Members are initialized in declaration order, whatever order this
// list is written in; the list follows it so that it reads truthfully.
// The full order is: courses_ and students_ (not in the list, so they are
// default-constructed, as empty stores), then notifier_, service_, and
// console_. If make_notifier threw, the two stores already built would be
// destroyed and no App would exist.
App::App(const Config& config, std::ostream& out)
// make_notifier returns a std::unique_ptr, and notifier_ takes
// ownership of the new notifier object from it.
: notifier_{make_notifier(config.notifier, out)},
// *notifier_ is the notifier object itself (the unique_ptr is
// dereferenced). The service keeps its address and the address of
// each store; it owns none of them.
service_{courses_, students_, *notifier_},
// The console keeps the address of service_, seen as the driving
// port type, core::EnrollmentUseCases.
console_{service_} {}
How this code works: Building the App, then one command through it

app::App application{*config, std::cout}; in main does all of this, in this order:

Step Member Built from Refers to (does not own)
1 courses_ nothing: an empty store nothing
2 students_ nothing: an empty store nothing
3 notifier_ make_notifier(config.notifier, out) out, for the stream notifier
4 service_ courses_, students_, *notifier_ all three
5 console_ service_ service_

Every “refers to” entry is a member built in an earlier row, or out, which main keeps alive for the whole run. The App owns everything in the table; the only part created on the heap, with std::make_unique, is the notifier, owned through notifier_.

Then application.run("enroll S3 CS101"):

  1. App::run forwards the line to console_.run. The App takes no part in the command; it only owns the parts.
  2. The console, a driving adapter, parses the words and calls enroll on the service through the driving port.
  3. The service looks up the student and a copy of the course through the store ports, which here are students_ and courses_, lets the course decide (both seats are taken, so S3 is waitlisted at position 1), saves the changed copy back into courses_, and calls notify on the Notifier port.
  4. Which notify runs was decided once, in step 3 of the table. With --notify=stream it is StreamNotifier::notify, which writes the notify S3: ... line to out; with --notify=none it is SilentNotifier::notify, which does nothing. The service cannot tell the difference.
  5. The reply goes back up through the console and App::run to main.

When main ends, the rows are destroyed from 5 back to 1, so each member is gone before anything it refers to.

service_ is given *notifier_, which is safe only because notifier_ is declared, and therefore built, before service_. courses_ and students_ are not in the list; they are default-constructed first, because they are declared first.

service_ holds pointers to courses_, students_, and the notifier object, and console_ holds a pointer to service_. A copy or a move of App made member by member would copy those pointers, still aimed at the original’s members. Commands sent to the new App would change the old one’s stores, and when the old one was destroyed the new one would dangle.

Copying was never possible here: the std::unique_ptr member cannot be copied, so the compiler would not generate a copy constructor anyway. Moving is the real danger. Without the two = delete lines, App would get an implicit move constructor that moves each member, compiles without a warning, and leaves exactly the dangling pointers described above. Declaring the copy operations, even as deleted, suppresses the implicit moves, and a move then selects the deleted copy and fails to compile. The test file states this so that a later edit cannot quietly undo it:

Compiled: these two lines are at the top of tests/test_app.cpp, so the test program does not build if App becomes copyable or movable.

// static_assert checks a condition while the program is compiled: if it
// is false, the build stops with an error. std::is_copy_constructible_v<T>
// is true when a T can be built as a copy of another T, and
// std::is_move_constructible_v<T> when it can be built by moving one
// (a move also counts if it would quietly fall back to a copy). The `!`
// asks for "not": App must allow neither.
static_assert(!std::is_copy_constructible_v<app::App>);
static_assert(!std::is_move_constructible_v<app::App>);

Moving could be made safe only by writing a move constructor that builds a new service_ and console_ around the moved members, because the core classes have no setters, and the moved-from App would be left broken. That is code to maintain for no gain: the graph is built once, in place, and never needs to move. If it must be handed around, hold it in a std::unique_ptr<App>; the object stays where it is and only the pointer moves.

The configuration is plain values, read before anything is built:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

config.hpp
// Which notifier to build: `stream` writes each message to the output,
// `none` drops every message (a rehearsal run). A name for a choice, not an
// object, so deciding costs nothing.
enum class NotifierChoice { stream, none };
// Everything the composition root needs to know to choose adapters.
// Plain values: reading the configuration builds no objects.
struct Config {
NotifierChoice notifier = NotifierChoice::stream;
};
// Reads the command-line arguments that follow the program name.
// Returns no value if any argument is not recognized.
// The only arguments it knows are --notify=stream and --notify=none. With
// no arguments it returns the defaults (stream), and if an option is given
// twice the last one wins. std::optional<Config> is "a Config, or nothing":
// a refusal is an empty optional, not an exception.
std::optional<Config> parse_config(const std::vector<std::string_view>& args);

A small factory turns the choice into an object. It is the only code that names both notifier classes:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

notifier_factory.hpp
// Chooses the notifier at run time. The caller owns the result, which
// is never null. `out` must outlive it.
// The return type is a std::unique_ptr to the port, core::Notifier, so
// the caller gets an owned object without learning its class. Only the
// stream notifier uses `out`; the silent one ignores it. Throws
// std::invalid_argument for a choice it does not know.
std::unique_ptr<core::Notifier> make_notifier(NotifierChoice choice, std::ostream& out);

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

notifier_factory.cpp
// The one place that names both concrete notifier classes. Each case
// creates the object on the heap with std::make_unique and returns it.
std::unique_ptr<core::Notifier> make_notifier(NotifierChoice choice, std::ostream& out) {
switch (choice) {
// make_unique<StreamNotifier>(out) passes `out` to the StreamNotifier
// constructor. The unique_ptr<StreamNotifier> it returns converts to the
// unique_ptr<core::Notifier> return type, because a StreamNotifier is a
// Notifier; ownership moves to the caller.
case NotifierChoice::stream: return std::make_unique<adapters::StreamNotifier>(out);
case NotifierChoice::none: return std::make_unique<SilentNotifier>();
}
// Not reached while every choice is handled above. Refuse rather than
// guess: a rehearsal that quietly sent messages would be worse.
throw std::invalid_argument{"make_notifier: unknown notifier choice"};
}

The rehearsal notifier is a null object: it implements the port and does nothing, so the service needs no if (notifications_enabled) anywhere.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

silent_notifier.hpp
// A driven adapter that drops every message: a null object for runs
// where nobody should be told anything, such as a rehearsal.
// `final`: nothing derives from it. It has no members, so it owns nothing
// and needs no constructor.
class SilentNotifier final : public core::Notifier {
public:
// The parameters have no names because they are never used, which also
// keeps the compiler from warning about unused parameters. The empty
// body {} is the whole behaviour: the message is accepted and dropped.
void notify(const domain::StudentId&, std::string_view) override {}
};

The service receives a Notifier&, stores it as a pointer, and never learns which class it got. That is the whole benefit of injection here: the run-time choice is made in one function, and the core is the same compiled code in both modes.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
int main(int argc, char* argv[]) {
// 1. Read the configuration. Nothing has been built yet, so a bad
// argument costs nothing to refuse.
// argv holds argc character strings, and argv[0] is the program's name. The
// range from argv + 1 up to argv + argc is every argument after it;
// the vector constructor makes one string_view for each, pointing at
// the original text (no copies). With no arguments the range is empty.
const std::vector<std::string_view> args(argv + 1, argv + argc);
const std::optional<app::Config> config = app::parse_config(args);
if (!config) {
std::cerr << "usage: arch_enrollment_composition_root [--notify=stream|none]\n";
return 2;
}
// 2. Build the whole object graph in one statement.
// *config reads the Config inside the optional; this is safe because
// the empty case returned above. application is a local object, so
// main owns the whole graph, and std::cout outlives it.
app::App application{*config, std::cout};
// 3. Run. The same script as version 0; with the default
// configuration the output must be the same text.
constexpr std::string_view script[] = {
"course CS101 2 Software Design",
"student S1 Ada Lovelace",
"student S2 Grace Hopper",
"student S3 Alan Turing",
"student S4 Barbara Liskov",
"enroll S1 CS101",
"enroll S2 CS101",
"enroll S3 CS101",
"enroll S4 CS101",
"enroll S3 CS101",
"enroll S9 CS101",
"drop S1 CS101",
"report CS101",
"drop S4 CS101",
"enroll S1 CS999",
"report CS101",
};
for (const std::string_view line : script) {
std::cout << "> " << line << '\n';
const std::string reply = application.run(line); // may print notifications first
std::cout << reply << '\n';
}
} // application is destroyed here, its members in reverse order

The order is deliberate:

  1. Read the configuration first. An unknown argument is refused with exit status 2 before any object of the graph exists, so there is nothing to undo. A CTest test runs the program with --notify=email and expects it to fail (any failing exit status passes that test).
  2. Build the graph in one statement. After that line, every object exists and every reference is valid, or the constructor threw. If a constructor throws, the members already constructed are destroyed in reverse order as the exception leaves the constructor, so a caller that catches it is left with nothing half-built. This main does not catch, so an exception here ends the program through std::terminate; whether the stack is unwound first is up to the implementation.
  3. Run. No code after the build creates or replaces a long-lived object.

With no arguments, the output is the same as version 0’s:

Expected output
> course CS101 2 Software Design
ok: course CS101 added
> student S1 Ada Lovelace
ok: student S1 added
> student S2 Grace Hopper
ok: student S2 added
> student S3 Alan Turing
ok: student S3 added
> student S4 Barbara Liskov
ok: student S4 added
> enroll S1 CS101
notify S1: you have a seat in CS101 Software Design
ok: S1 enrolled in CS101
> enroll S2 CS101
notify S2: you have a seat in CS101 Software Design
ok: S2 enrolled in CS101
> enroll S3 CS101
notify S3: you are number 1 on the waitlist for CS101 Software Design
ok: S3 waitlisted for CS101 (position 1)
> enroll S4 CS101
notify S4: you are number 2 on the waitlist for CS101 Software Design
ok: S4 waitlisted for CS101 (position 2)
> enroll S3 CS101
refused: S3 is already on the waitlist for CS101
> enroll S9 CS101
refused: no student S9
> drop S1 CS101
notify S3: a seat opened; you are enrolled in CS101 Software Design
ok: S1 dropped CS101; S3 moved from the waitlist
> report CS101
ok: CS101 Software Design, 2/2 seats taken
seated: S2 Grace Hopper, S3 Alan Turing
waitlist: S4 Barbara Liskov
> drop S4 CS101
ok: S4 left the waitlist for CS101
> enroll S1 CS999
refused: no course CS999
> report CS101
ok: CS101 Software Design, 2/2 seats taken
seated: S2 Grace Hopper, S3 Alan Turing
waitlist: (none)
One run of the program: configuration is read, App builds its members in declaration order, commands run, and members are destroyed in reverse order
Text description of the diagram

A sequence diagram of one run. main parses the configuration from argv, then constructs App with the configuration and std::cout. App constructs courses_ and students_, then make_notifier creates the notifier, then App constructs the service with the stores and the notifier, then the console with the service. main asks App to run each command; App passes the line to the console, which calls one use case on the service, such as add_course, enroll, or report. At the end of main, App is destroyed: first console_, then service_, then notifier_, then students_ and courses_, the reverse of construction.

Diagram source (Mermaid)
sequenceDiagram
participant M as main
participant A as App
participant S as stores
participant N as notifier
participant V as service
participant C as console
M->>M: parse_config from argv
M->>A: construct with config and std::cout
A->>S: construct courses_ and students_
A->>N: make_notifier creates the notifier
A->>V: construct with the stores and the notifier
A->>C: construct with the service
M->>A: run each command
A->>C: run the line
C->>V: call one use case
M->>A: end of main, destroy
A->>C: destroy console_
A->>V: destroy service_
A->>N: destroy notifier_
A->>S: destroy students_ and courses_

The hexagonal example’s unit tests stay as they were: the core with in-memory adapters and a recording notifier, the console with a fake core. What they cannot catch is a mistake in the wiring itself, such as the factory returning the wrong notifier, or a configuration option that is parsed but never reaches the factory. Wiring tests build the real graph and send it a few commands:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_app.cpp
// Wiring tests: they build the real graph, as main does, and check that
// a command reaches the core and the chosen notifier.
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure
// if the condition is false, and LLD_CHECK_EQ(actual, expected) records
// one if the two are not equal (==) and prints both. They come from the
// site's small test header, lld_test.hpp. seat_one_student, a helper above
// this snippet, sends three commands (add a one-seat CS101, add S1, enroll
// S1) and returns the three replies joined, one per line.
//
// The stream notifier: proves the one notification reaches the stream the
// App was given, and the enroll reply is among the replies. find returns
// std::string::npos when the text is not there.
LLD_TEST(the_default_graph_sends_notifications_to_the_stream) {
std::ostringstream out;
app::App application{app::Config{app::NotifierChoice::stream}, out};
const std::string replies = seat_one_student(application);
LLD_CHECK_EQ(out.str(), std::string{"notify S1: you have a seat in CS101 Software Design\n"});
LLD_CHECK(replies.find("ok: S1 enrolled in CS101") != std::string::npos);
}
// Two graphs built side by side, one per choice. Proves that swapping the
// notifier changes nothing the console replies, and that the silent one
// writes nothing at all.
LLD_TEST(the_silent_graph_gives_the_same_replies_and_no_notifications) {
std::ostringstream loud_out;
std::ostringstream silent_out;
app::App loud{app::Config{app::NotifierChoice::stream}, loud_out};
app::App silent{app::Config{app::NotifierChoice::none}, silent_out};
LLD_CHECK_EQ(seat_one_student(silent), seat_one_student(loud));
LLD_CHECK(silent_out.str().empty());
}
// Two Apps share one output stream but nothing else. A course added
// through `first` must not exist in `second`: each App owns its own
// stores, so nothing is hidden in a global.
LLD_TEST(two_graphs_share_no_state) {
std::ostringstream out;
app::App first{app::Config{app::NotifierChoice::none}, out};
app::App second{app::Config{app::NotifierChoice::none}, out};
seat_one_student(first);
LLD_CHECK_EQ(second.run("report CS101"), std::string{"refused: no course CS101"});
}

Because App takes its output stream as a parameter instead of writing to std::cout directly, a test can read what the notifier wrote. The last test checks that two graphs in one process share no state: a course added through one is not visible through the other, which a global store or a service locator would break. The two share an output stream on purpose, because the stream is injected.

Keep wiring tests few and broad. One or two commands per run-time choice show that the parts are connected; the rules are already tested where they live.

The configuration parser is plain values in and out, so its tests need no graph at all:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_config.cpp
// Configuration is plain data, so it is tested without building any App.
// A brace list such as {"--notify=none"} becomes the vector of string_view
// arguments that parse_config takes; {} is an empty vector, as if the
// program were run with no arguments. `config->notifier` reads a member of
// the Config inside the optional.
//
// No arguments: proves a Config is returned, holding the default (stream).
LLD_TEST(no_arguments_mean_the_default_configuration) {
const std::optional<app::Config> config = app::parse_config({});
LLD_CHECK(config.has_value());
LLD_CHECK(config->notifier == app::NotifierChoice::stream);
}
// One known argument: proves --notify=none selects the silent notifier.
LLD_TEST(the_notifier_can_be_turned_off) {
const std::optional<app::Config> config = app::parse_config({"--notify=none"});
LLD_CHECK(config.has_value());
LLD_CHECK(config->notifier == app::NotifierChoice::none);
}
// An unknown value, and a known one followed by an unknown word: both
// return an empty optional, so one bad argument refuses the whole line.
LLD_TEST(an_unknown_argument_is_refused) {
LLD_CHECK(!app::parse_config({"--notify=email"}).has_value());
LLD_CHECK(!app::parse_config({"--notify=none", "extra"}).has_value());
}

Every test that builds objects is a small composition root of its own, choosing fakes where main chooses real adapters. That is not duplication to remove: each root builds the graph its purpose needs.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

CMakeLists.txt
# The composition root of the hexagonal version, grown up: the core and
# the adapters are the hexagonal example's libraries, unchanged. Only the
# code that chooses, builds, and owns the objects is new.
add_library(arch_comp_root_app STATIC app.cpp config.cpp notifier_factory.cpp)
target_include_directories(arch_comp_root_app PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(arch_comp_root_app PUBLIC arch_hex_core arch_hex_memory arch_hex_stream arch_hex_console)
lld_add_example(arch_enrollment_composition_root SOURCES main.cpp EXPECTED_OUTPUT expected_output.txt)
target_link_libraries(arch_enrollment_composition_root PRIVATE arch_comp_root_app)
lld_add_test(arch_comp_root_config_tests SOURCES tests/test_config.cpp)
target_link_libraries(arch_comp_root_config_tests PRIVATE arch_comp_root_app)
lld_add_test(arch_comp_root_app_tests SOURCES tests/test_app.cpp)
target_link_libraries(arch_comp_root_app_tests PRIVATE arch_comp_root_app)
# main refuses an argument it does not know, before building anything.
add_test(NAME arch_comp_root_refuses_unknown_argument
COMMAND arch_enrollment_composition_root --notify=email)
set_tests_properties(arch_comp_root_refuses_unknown_argument PROPERTIES
WILL_FAIL TRUE LABELS "test")

Hidden dependencies: globals and service locators

Section titled “Hidden dependencies: globals and service locators”

A dependency is hidden when a class uses something its constructor does not ask for. The two usual ways to hide one are a global (often a singleton) and a service locator: a registry that code asks for its collaborators by type.

Way of getting a collaborator Visible in the constructor A missing one is found Two graphs in one process
constructor injection yes when compiling independent
service locator no when the code runs share the registry
global or singleton no sometimes never (it always exists) share the one object

A service locator is not always wrong. Some frameworks give plug-ins a registry because the host cannot know their constructors in advance. Inside your own program, where you write both the class and the composition root, it trades a compile-time check for a run-time lookup and buys nothing.

Objects that live shorter than the program

Section titled “Objects that live shorter than the program”

Everything in this graph lives for the whole run. Larger programs also need objects per request: a report builder for one command, a database transaction for one use case. The composition root cannot build those in advance, because they do not exist yet.

The answer is still injection. Inject something that makes them, such as a small factory interface, or a std::function that returns a std::unique_ptr, and let the class call it when it needs a new object. The class owns what it makes and destroys it at the end of the call. The composition root decides which factory, so tests can still substitute fakes. The difference from a locator is that the factory is in the constructor’s parameter list, so the dependency is visible.

Local variables in main are enough when the graph has a handful of objects, no choices made at run time, and no need to build it anywhere else. The hexagonal version’s main is that case. Adding an App class there would be a class with one user and nothing to hide.

A class like App earns its place when:

  • tests need to build the same graph that main builds;
  • some adapters are chosen from configuration;
  • the program needs more than one independent graph, for example one per tenant, or one per test in a single test program;
  • the declarations are numerous enough that their order needs a comment and a place of its own.

When the root itself grows large, split it into functions that each build one part, such as make_storage(const Config&), still as plain code. C++ rarely needs a dependency injection container: a constructor call is the injection, and the compiler checks every argument. A container is worth considering mainly when the graph is built from configuration files or plug-ins the code cannot name, or when it is large and has many scoped lifetimes, such as objects per request.

  • Declarations out of dependency order. A member that refers to one declared below it may be used before it is built, or after it is gone. Storing its address early is legal, which is why compilers often say nothing; using it is undefined behaviour. Order the members by what they refer to, and keep the initializer list in the same order.
  • A copyable or movable graph. If the owner of the graph can be copied or moved, the new object refers to the old one’s members. Delete the copy operations, which also suppresses the moves.
  • Choosing adapters outside the root. An if (rehearsal) inside the service, or a new StreamNotifier in an adapter, spreads the wiring through the program. Make the choice once, in the root.
  • Building objects during the run. A long-lived object created half-way through, on first use, has a lifetime nobody planned. Build long-lived objects up front; inject a factory for short-lived ones.
  • Reaching through the root. Passing the root object around so that code can fetch what it needs turns it into a service locator.
  • Writing straight to std::cout inside the graph. Take the stream as a parameter, so that a test can supply its own.
  • Notifications can also go to a log file. Add a NotifierChoice::file and a --notify-to=PATH option. App gains a std::ofstream member declared above notifier_, because the stream notifier will refer to it. Nothing outside the composition root changes.
  • Courses must be stored in a database. Add a database adapter for CourseStore. If the choice is made at run time, courses_ becomes a std::unique_ptr<core::CourseStore> built by a factory, like the notifier. The service is unchanged.
  • Enrollment closes at a deadline. The service now needs the current time. Add a Clock port, inject it, and give App a system clock member; tests pass a fake clock. The exercise below starts from the hidden version of this change.
  • One process serves two universities. Build two App objects, one per university. Because nothing in the graph is global, this works without changes; the wiring test that checks two graphs share no state is a start, and a real version would test each store and notifier.

Exercise: Find the hidden dependencies

A colleague added an enrollment deadline to the service. A flawed sketch, illustrative and not compiled:

EnrollResult EnrollmentService::enroll(const std::string& student,
const std::string& course) {
// Reads the computer's current date and time.
const auto now = std::chrono::system_clock::now();
// Settings::instance() returns the one Settings object of the program
// (a singleton), and deadline() is the time enrollment closes.
if (now > Settings::instance().deadline()) {
// Writes the message to the audit log.
AuditLog::write("late enrollment refused for " + student);
return {EnrollStatus::closed, 0}; // a new status for this rule
}
// ...the rest as before...
}
  1. List every dependency of enroll that its class’s constructor does not show.
  2. For each one, describe a test you would want to write and why this code makes it hard or impossible.
  3. Redesign: say what the constructor should take, where each real object is created and who owns it, and what a test passes instead.
Show the explained answer
  1. Three hidden dependencies: the system clock (std::chrono::system_clock::now()), the settings singleton that holds the deadline, and the audit log, a global function that writes somewhere.

  2. Tests the code blocks:

    • “Enrollment one second before the deadline succeeds, one second after it is refused” needs control of the time. With the real clock, the test passes or fails depending on the day it runs.
    • “Each university has its own deadline” needs two settings in one process; the singleton allows one.
    • “A late attempt is audited” needs to read what was logged; a global writer gives the test nothing to read, and every test that triggers a refusal writes to the real log.
  3. One possible redesign:

    • A Clock port in the core with virtual std::chrono::system_clock::time_point now() const = 0;. The constructor takes const Clock&. App owns a SystemClock member declared above service_; a test passes a FakeClock set to any time.
    • The deadline is data, not a service: pass it to the constructor as a std::chrono::system_clock::time_point, read from the configuration by main. Two App objects can have two deadlines.
    • Auditing is either a driven port (AuditLog&, owned by App, recorded by a fake in tests), or it is dropped from the service entirely and done by the console, if a refusal reply already carries the information. Choose by asking whether auditing is a rule of the registrar’s office or a detail of this front end.

    After the change, the constructor reads EnrollmentService(CourseStore&, StudentRegister&, Notifier&, const Clock&, time_point deadline), or with an AuditLog& as well, and every dependency is visible where the object is built.

  • The composition root is the one place that creates the program’s objects and connects them, next to main. Nothing else names the concrete adapters together.
  • Draw the ownership graph: every object has one owner, and every non-owning reference must point at something destroyed later.
  • A class that owns the graph as members gets the order right from declaration order: members are built top to bottom and destroyed bottom to top. GCC may not warn when that order is wrong.
  • Such a class must refuse copying and moving, because its members point at each other; a unique_ptr member alone blocks only the copy.
  • Read configuration before building, choose adapters in a factory, and hold a run-time choice in a std::unique_ptr.
  • Wiring tests build the real graph; every test is a small composition root of its own.
  • Globals and service locators hide dependencies and move errors from compile time to run time. Inject factories for objects that live shorter than the program.