Skip to Content
Architecture Patterns with Python
book

Architecture Patterns with Python

by Harry Percival, Bob Gregory
March 2020
Intermediate to advanced content levelIntermediate to advanced
301 pages
7h 10m
English
O'Reilly Media, Inc.
Book available
Content preview from Architecture Patterns with Python

Chapter 13. Dependency Injection (and Bootstrapping)

Dependency injection (DI) is regarded with suspicion in the Python world. And we’ve managed just fine without it so far in the example code for this book!

In this chapter, we’ll explore some of the pain points in our code that lead us to consider using DI, and we’ll present some options for how to do it, leaving it to you to pick which you think is most Pythonic.

We’ll also add a new component to our architecture called bootstrap.py; it will be in charge of dependency injection, as well as some other initialization stuff that we often need. We’ll explain why this sort of thing is called a composition root in OO languages, and why bootstrap script is just fine for our purposes.

Figure 13-1 shows what our app looks like without a bootstrapper: the entrypoints do a lot of initialization and passing around of our main dependency, the UoW.

Tip

If you haven’t already, it’s worth reading Chapter 3 before continuing with this chapter, particularly the discussion of functional versus object-oriented dependency management.

apwp 1301
Figure 13-1. Without bootstrap: entrypoints do a lot
Tip

The code for this chapter is in the chapter_13_dependency_injection branch on GitHub:

git clone https://github.com/cosmicpython/code.git cd code git checkout chapter_13_dependency_injection # or to code along, checkout the previous chapter: git checkout chapter_12_cqrs ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python Architecture Patterns

Python Architecture Patterns

Jaime Buelta
Data Structures & Algorithms in Python

Data Structures & Algorithms in Python

John Canning, Alan Broder, Robert Lafore

Publisher Resources

ISBN: 9781492052197Errata PageSupplemental Content