Skip to content

Architectural patterns are not GoF patterns - dependency injection, Repository, Unit of Work

Difficulty: Intermediate

Key concepts

  • architectural pattern
  • levels of design
  • dependency injection
  • composition root
  • Repository
  • Unit of Work
  • Three levels of reusable design: idioms, design patterns, and architectural patterns, and how to tell which level a technique belongs to.
  • Why dependency injection, Repository, and Unit of Work are architectural techniques, not classic patterns, and which classic patterns they are built from.
  • What each of the three decides, when it helps, and when a smaller program does not need it.
  • Where the full treatment of each is: the pages on dependency injection and dependency inversion now, and the planned architecture pages later.

Reusable design ideas come in three sizes. The patterns overview introduced them; this page puts them side by side.

Level What it shapes Who notices a change Examples
Idiom how one class or function is written, in one language the code that uses that class RAII, PImpl, type erasure, policy-based design
Design pattern how a few classes collaborate to solve one design problem the classes in the pattern and their callers Strategy, Observer, Adapter, Builder, State
Architectural pattern how the whole application is split into parts, and how the parts connect many modules, the build, often the team layers, ports and adapters, dependency injection, Repository, Unit of Work

Three questions place a technique:

  1. How much code must agree on it? One class: an idiom. A handful of collaborating classes: a design pattern. Every module that stores data, or every use case, or main and the build files: an architectural pattern.
  2. Is it tied to one language’s rules? RAII needs destructors that run at a known point. Strategy and Repository can be written in almost any language with interfaces.
  3. What does it cost to undo? Replacing a Strategy with a lambda is an afternoon. Removing the Repository layer from an application changes every use case that reads or writes data.

The levels nest. An architectural pattern is usually built from classic patterns, and in C++ those patterns are written with idioms. A Repository’s implementation is an Adapter over a database library, and its lifetime is managed with RAII.

  • It picks the right comparison. “Strategy or dependency injection?” is not a real choice: injection is how a Strategy object reaches the class that uses it. The real choices are within a level: Strategy or a function parameter; Repository or direct queries.
  • It puts the decision in the right place. An architectural decision shows up in module boundaries, #include and link lines, and main, not inside one class. Making it class by class gives an application where every part makes it differently.
  • It sets expectations about cost. An idiom can be adopted in one pull request. An architectural pattern is a commitment for the whole application, so it needs a requirement that justifies it.

What it is. An object receives the collaborators it uses, usually through its constructor, instead of creating or finding them itself. The dependency injection page builds this with an alarm clock whose time source and bell are passed in, so that tests can pass fakes.

Why it is architectural. For one class, injection is just a constructor parameter. It becomes an architectural decision when the whole application follows it: every part receives what it needs, and one place, usually main, creates the real objects and connects them. That place is called the composition root. The decisions are about the whole program: where the composition root is, who owns each object, and in what order they are created and destroyed.

What it is built from. No fixed set of classes. Injection carries whatever the class needs: a Strategy, a Repository, a logger, which may be a Null Object, or an Observer’s listener. Unlike a classic pattern, injection has no fixed set of collaborating classes; it says only that the client receives its services from whoever assembles the program.

In C++, injection is also an ownership decision. A collaborator passed by reference is borrowed and must outlive the object; one passed as a std::unique_ptr is owned by it. The composition root makes these lifetimes visible in one function.

A container is optional. Some languages use a dependency injection container, a library that creates objects from configuration. In C++ the usual container is main: plain code that creates objects in order, which the compiler checks and a reader can follow.

Not the same as dependency inversion. Inversion decides which module owns the interface; injection decides how an object gets an implementation. The Dependency Inversion Principle page shows each without the other. The page on dependency injection and composition roots covers wiring a whole application.

What it is. An interface, owned by the business rules, that lets them store and find domain objects as if they were in a collection, without knowing how or where they are stored. Its implementations live outside the rules: one for the database, often one in memory for tests. The name is used this way in Martin Fowler’s Patterns of Enterprise Application Architecture, and Eric Evans’s Domain-Driven Design describes it as one of the building blocks of a domain model, alongside entities, value objects, aggregates, and factories.

The shape, as a sketch (not compiled):

interface (abstract class) OrderRepository

owned by the orders rules; speaks in Orders, not rows

Member functions

  • std::optional<Order> find(const OrderId& id) const; std::nullopt if there is none
  • void add(Order order); a new order
  • void save(const Order& order); an existing order, changed; under a Unit of Work, this only records the change until commit

class SqlOrderRepository

in the database module: implements the interface

Data members

  • DatabaseConnection* connection_; non-owning, never null: borrowed from the composition root; a pointer keeps the class assignable

Member functions

  • std::optional<Order> find(const OrderId& id) const; runs a query, builds an Order
  • void add(Order order);
  • void save(const Order& order);

class InMemoryOrderRepository

for tests: the same interface over a std::map

Data members

  • std::map<OrderId, Order> orders_; owned

Member functions

  • std::optional<Order> find(const OrderId& id) const;
  • void add(Order order);
  • void save(const Order& order);
A sketch of a Repository: the interface is in the orders module, and each implementation is in its own module

Why it is architectural. It draws the boundary between the business rules and storage for the whole application: every use case that reads or writes orders goes through it, and the rules’ module stops depending on the database library. That is the Dependency Inversion Principle applied to persistence.

What it is built from. An interface owned by the rules (dependency inversion); an implementation that is an Adapter from that interface to the database library; often a Factory or the composition root to choose the implementation. None of these is the Repository itself; the Repository is the decision to put all storage behind interfaces shaped like collections of domain objects.

When it helps. The rules are worth testing without a database; storage may change; several use cases share the same objects.

When it does not.

  • A small program, or one whose “rules” are mostly reading and writing rows, gains a layer with nothing to hide.
  • Reports and searches that combine many objects fit a collection-like interface badly. A separate query interface, which returns read-only results shaped for the screen, is often clearer than a Repository with dozens of find_by_... functions.
  • A Repository per database table is a different technique. A Repository speaks in whole domain objects, which may span several tables.

Repository and Unit of Work builds both in C++, with in-memory and file-backed implementations and tests.

What it is. An object that keeps track of everything one business operation changes, the new, changed, and removed objects, and commits those changes together, or not at all, usually in one database transaction. It also decides what happens when another operation has changed the same data in the meantime. It is described in the same Fowler book as Repository.

A sketch of the shape (not compiled):

interface (abstract class) UnitOfWork

owned by the application rules

Member functions

  • OrderRepository& orders(); repositories that record changes in this unit
  • StockRepository& stock();
  • void commit(); all recorded changes, together; throws if they cannot be saved

class PlaceOrder

a use case: one business operation, one unit of work per run

Member functions

  • OrderId run(UnitOfWork& work, const Cart& cart); a fresh unit for each call: changes orders and stock, then commits once
A sketch of a Unit of Work: the use case records changes through it and commits once at the end

Why it is architectural. It decides the transaction boundary for every use case: what counts as one change, who begins and commits it, and what happens on failure. Those rules must be the same across the application, or some operations will save half their changes.

What it is built from. A list of pending changes, which is close to a list of Commands applied at commit time; repositories that report what they change; and, in C++, an RAII guard that rolls back if the operation ends without committing, for example because an exception was thrown.

When it helps. One operation changes several objects that must stay consistent: placing an order reduces stock and records a payment, and saving only some of that would leave the data wrong.

When it does not. Each operation changes one object, or the database’s own transaction, begun and committed in one function, is already enough. Do not hold a database transaction open while waiting for a user: it blocks other users and fails in ways that are hard to test. A Unit of Work can collect changes across that wait and open the transaction only at commit, but then it must check at commit that nobody else changed the same data (optimistic locking).

The rules own the interfaces, the database module implements them, and main creates the real objects and passes them in
Text description of the diagram

A component diagram with three groups. The orders module holds the business rules: the PlaceOrder use case and two interfaces, OrderRepository and UnitOfWork; the use case uses both interfaces. The database module holds SqlOrderRepository and SqlUnitOfWork, which implement those interfaces, and the DatabaseConnection, which both borrow; the SqlUnitOfWork creates the SqlOrderRepository and hands it out. The composition root, main, creates the connection and the use case, and for each operation creates a unit of work and passes it to the use case’s run function. Every arrow between the orders module and the database module points from the database module to the orders module: the rules do not depend on the database.

Diagram source (Mermaid)
flowchart LR
subgraph Main [main: the composition root]
  M["creates the connection and the use case,<br/>then a unit of work for each operation"]
end
subgraph Rules [orders module: business rules]
  UC["PlaceOrder use case"]
  RI["OrderRepository interface"]
  UI["UnitOfWork interface"]
end
subgraph Db [database module]
  SR["SqlOrderRepository"]
  SU["SqlUnitOfWork"]
  C["DatabaseConnection"]
end
UC -->|uses| RI
UC -->|uses| UI
SR -.->|implements| RI
SU -.->|implements| UI
SU -->|creates and hands out| SR
SR -->|borrows| C
SU -->|borrows| C
M -->|creates| UC
M -->|creates per operation, passes to run| SU
M -->|creates| C

Read the arrows between the groups:

  • Dependency inversion is the direction: the database module depends on the rules’ interfaces, never the other way round.
  • Dependency injection is how the use case gets real objects: main passes a unit of work into each call, and the unit of work hands out the repositories.
  • Repository and Unit of Work are what the interfaces are: storage shaped like collections, and one commit per operation.

None of the three needs the others in principle, but they are usually used together, because each solves part of one problem: keeping the business rules independent of storage, and still saving their changes correctly.

  • “Dependency injection is a framework.” It is passing collaborators in. A container is one way to do the wiring, and in C++ it is rarely needed.
  • “We use the Strategy pattern, so we use dependency injection,” or the other way round. A Strategy may be injected, and an injected object may be a Strategy, but one is a design pattern and the other is how objects are connected.
  • “A Repository is a class with create, read, update, and delete for each table.” That is a table data gateway, or a data access object per table. A Repository is shaped by the domain objects and owned by the rules; in domain-driven design there is usually one per aggregate, not one per table.
  • A Repository that returns database types. An interface that returns rows, cursors, or SQL fragments has moved the database into the rules, which is what it was meant to prevent.
  • Using all three in a small tool. A 300-line command-line program that reads one file and writes another gains interfaces, a composition root, and a transaction layer, and hides nothing.
  • Calling them “GoF patterns.” They are not in the 1994 catalogue, and they are not at its level. Treating them as one more Strategy hides how much of the application they commit you to.
  • A second storage engine is needed: with a Repository, write another implementation and change a few lines in main, provided the interface does not expose the first engine’s features. Without one, every use case changes.
  • Tests must run without a database: inject in-memory repositories and a Unit of Work that commits to them. This is often the first reason a team adopts all three. In-memory fakes do not test the SQL mapping, so a few integration tests against the real database are still needed.
  • An operation must also send an email after saving: send it after commit succeeds, not inside the unit of work, so that a failed commit sends nothing. Where the email must not be lost, that leads to Event-driven application components.
  • The program stays small: do nothing. These techniques are worth their cost only when the application is large enough to have boundaries to protect.

Exercise: Classify techniques by level

For each technique, say whether it is an idiom, a design pattern (and which), an architectural pattern or technique, or none of these, and give the reason in one sentence.

  1. A std::lock_guard that unlocks a mutex at the end of a scope.
  2. main creates a SystemClock, a GpioBell, and an AlarmClock, and passes the first two into the third’s constructor.
  3. A rule, enforced by the build, that the orders library may not link to the database library.
  4. A shipping-cost calculator chosen at run time from configuration, behind a ShippingCost interface.
  5. Checkout records every change to stock, orders, and payments in one object, which saves them all in one transaction at the end, or none of them.
  6. RowWriter<CsvFormat>, a class template whose format is a template parameter.
  7. An InMemoryOrderRepository used by the tests of the order rules.
  8. A class that offers one simple function, pay, over a payment library with twenty functions.
  9. A team rule that no function may be longer than 40 lines.
Show the explained answer
  1. Idiom: RAII. It is one object’s lifetime, tied to C++ destructors.
  2. Architectural technique: dependency injection, with main as the composition root. The alarm clock receives its collaborators, and one place creates and connects the real objects.
  3. Architectural: a dependency rule between modules, as in layered and ports-and-adapters designs. It is about modules and the build, not a few classes. If the database module implements interfaces the orders module owns, it is dependency inversion enforced by the build.
  4. Design pattern: Strategy (behavioural). How the chosen strategy reaches the calculator’s user is a separate question, usually answered by injection.
  5. Architectural: Unit of Work. It sets the transaction boundary for an operation.
  6. Idiom: policy-based design. It is a Strategy chosen at compile time, written with C++ templates.
  7. Architectural: an implementation of a Repository, used as a test double. The Repository is the architectural decision; this class is one implementation of it.
  8. Design pattern: Facade (structural). It simplifies one subsystem for its callers. If its interface is owned by the rules and it translates to the library, it is also acting as an adapter at an architectural boundary.
  9. None of these. It is a style limit: it solves no recurring design problem and says nothing about which classes or parts exist or how they connect.
  • Reusable design comes at three levels: idioms shape one class in one language, design patterns shape a few collaborating classes, and architectural patterns shape how the whole application is split and connected.
  • Dependency injection passes collaborators in; as an architecture, one composition root, usually main, creates and connects the real objects. In C++ it also decides who owns each one.
  • A Repository puts storage behind interfaces owned by the rules and shaped like collections of domain objects.
  • A Unit of Work records the changes of one operation and commits them together.
  • These are built from classic patterns, such as Adapter, Factory, and Command, and they commit the whole application, so they need a requirement that justifies them.