Skip to content

Dependency Inversion Principle (DIP) ​

"A. High level modules should not depend upon low level modules. Both should depend upon abstractions. B. Abstractions should not depend upon details. Details should depend upon abstractions." — Robert C. Martin, The Dependency Inversion Principle, The C++ Report, May 1996

Summary: DIP says the code that holds your business policy should own the abstractions it needs, and the databases, frameworks and vendors should depend on those abstractions, not the other way round. Focus: Direction and ownership of dependencies; inversion vs injection vs IoC vs containers; composition root; injection styles; the service locator anti-pattern; ports and adapters and the Clean Architecture dependency rule; Go import graphs; Laravel's container (bind, singleton, scoped, contextual binding, #[Bind], #[Config]); Martin's stability metrics; DIP across services. Learning goal: Draw the import graph of a feature, see which arrows point the wrong way, move the interface to the side that owns the policy, wire everything in one composition root, and know when an abstraction costs more than it returns.

This page is the complete reference for the D in SOLID: Martin's 1996 column and its Copy/Button examples, the two things that get inverted (direction and ownership), the vocabulary that is constantly mixed up (dependency inversion, dependency injection, inversion of control, IoC container, service locator, composition root), how Go, PHP/Laravel, Java/Spring, C#/.NET, TypeScript/NestJS and Python wire dependencies, the architectural styles built on the rule (Cockburn's hexagonal architecture, Martin's Clean Architecture), the package metrics that measure it, and how it applies between services (consumer-owned contracts, anti-corruption layers). Neighbours: Open–Closed and Liskov are the two principles Martin derived DIP from; Interface Segregation keeps the owned abstractions small. The SOLID overview is at /design/solid/.

Page map ​

If you are looking forGo to
The principle and the vocabulary in tablesEverything in one minute
Why the arrows matterWhy DIP exists
Martin 1996, Fowler 2004, Cockburn 2005, Martin 2012, CheneyWhere it comes from
Direction, ownership, DI vs IoC vs container, injection styles, composition root, service locator, ports and adapters, stable abstractions, over-abstractionThe concepts, one by one
Go, Laravel, Spring, .NET, NestJS, Python wiring comparedPer-language and framework behaviour
Go and Laravel before/after codeGo, Laravel
Import cycles, container resolution, lifetimes, instability and abstractnessMechanics
Vendor SDK in the domain, framework in the domain, static calls, shared modelsSolving the classic problems
When to invert and when not toChoosing
Hexagonal, Clean Architecture, services, ACLIn architecture
Refactoring kata with real outputLab
Wrong beliefs, cheat sheet, termsMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

Four terms people mix up.

TermWhat it isKind of thingTiny example
Dependency Inversion (DIP)Policy owns the abstraction; details depend on itA design principle about the dependency graphcheckout defines OrderRepository; postgres implements it
Dependency Injection (DI)Someone else hands an object its dependenciesA techniqueNewCheckoutService(repo)
Inversion of Control (IoC)The framework calls your code, not the reverseA general property of frameworks ("Hollywood Principle")Laravel calls your controller; net/http calls your Handler
IoC / DI containerA library that builds object graphs for youA toolLaravel service container, Spring, .NET IServiceCollection, NestJS

What gets inverted.

AspectTraditional layeringInverted
Source dependency (import)Policy → detailDetail → abstraction owned by policy
Control flow at run timePolicy → detailStill policy → detail (unchanged)
Who defines the interfaceThe detail (or nobody)The policy, in its own language
Where concrete types are chosenInside the policy (new StripeGateway)In the composition root (main, service provider)
What a storage change touchesThe policyOne adapter and one line of wiring

The three things to do.

SituationDo this
Business code needs I/O (DB, HTTP, queue, clock)Declare a small interface in the business package; implement it in an adapter package
Building objectsConstructor injection everywhere; choose concrete types in one composition root
Tempted to call the container from business codeDon't: inject what you need instead (PSR-11 says "Users SHOULD NOT pass a container into an object")

Why DIP exists ​

In procedural layering the high-level module calls the low-level one and therefore imports it. That is natural, and it has a cost Martin names precisely: the module that holds "the important policy decisions and business models of an application" is the one forced to change when a low-level detail changes. Inversion keeps control flowing downward at run time while making the source dependency point upward, at an abstraction that the policy owns. The price is an extra interface and wiring code.

Policy depends on detailDetail depends on policy's abstraction
Fewer types; easy to follow in a debuggerOne more interface per seam
Changing the database edits business codeChanging the database edits one adapter
Unit tests need the real database or monkey-patchingUnit tests pass an in-memory fake
Policy cannot be reused with another detailPolicy reusable (Martin's Copy to disk, not only printer)
Vendor's types leak into the domainDomain speaks its own language; adapter translates
No wiring codeA composition root to maintain

The analogy we reuse on this page: wall sockets. A house does not depend on a specific lamp; a lamp does not depend on a specific house. Both depend on the socket standard, and that standard was written from the house's point of view, by the people who wire buildings, not by any lamp maker. A new lamp must fit the socket (details depend on abstractions); the house never changes (policy is stable). The electrician who decides which lamp goes in which room is the composition root. A travel adapter at the airport is an anti-corruption layer.

Three common misunderstandings, up front ​

  1. "DIP means using a DI container." A container is one way to wire. Passing a dependency to a constructor by hand in main is DIP and DI with no container at all; Go programs usually do exactly that.
  2. "Extract an interface from the concrete class and you're done." If the interface mirrors the vendor and lives next to the adapter, the policy still depends on the vendor's shape and package. The abstraction must be owned by, and phrased for, the high-level module.
  3. "Inversion changes who calls whom." At run time the policy still calls the database. What changes is the direction of the source code dependency and who owns the interface.

Where it comes from ​

Martin, 1996. Martin introduced DIP in his May 1996 C++ Report column as the structural consequence of OCP and LSP: depend on abstractions that are closed for modification, whose implementations are substitutable, and the dependency structure comes out "'inverted' with respect to the dependency structure that normally results from traditional procedural methods." His first example is a Copy program that reads from the keyboard and writes to a printer; asked to write to a disk file, the Copy module, which holds the real policy, must change. The fix: Copy depends on abstract Reader and Writer; Keyboard, Printer and Disk derive from them. The second, a Button controlling a Lamp, makes the button depend on a ButtonClient abstraction. He also notes that C's stdio.h (getchar/putchar) "is another example of dependency inversion".

Martin, 1994: measuring it. An earlier paper, OO Design Quality Metrics: An Analysis of Dependencies (October 1994), turns the idea into numbers: afferent and efferent couplings, instability I = Ce / (Ca + Ce), abstractness A, and the main sequence where they balance. It argues that stable packages should be abstract so they can be extended. Martin later named these the Stable Dependencies and Stable Abstractions principles in his books (that naming is from his later writing, not the 1994 paper, which says "categories" rather than packages).

Fowler, 2004: naming the technique. Martin Fowler's article Inversion of Control Containers and the Dependency Injection pattern separated the general idea from the specific technique: "Inversion of Control is too generic a term, and thus people find it confusing. As a result with a lot of discussion with various IoC advocates we settled on the name Dependency Injection." He described constructor, setter and interface injection and compared them with the Service Locator. His bliki entry on IoC calls the general phenomenon the "Hollywood Principle - 'Don't call us, we'll call you'".

Cockburn, 2005: ports and adapters. Alistair Cockburn's Hexagonal Architecture asks the application "to work without either a UI or a database so you can run automated regression-tests against the application", with technology-specific adapters converting signals at ports the application defines. The application "is blissfully ignorant of the nature of the input device".

Martin, 2012: the dependency rule. The Clean Architecture unified hexagonal, onion and BCE architectures under one rule:

"This rule says that source code dependencies can only point inwards. Nothing in an inner circle can know anything at all about something in an outer circle." — Robert C. Martin, The Clean Architecture, 13 August 2012

Seemann: the composition root. Mark Seemann's definition, from Dependency Injection Principles, Practices, and Patterns, summarised on his blog:

"A Composition Root is a (preferably) unique location in an application where modules are composed together." — Mark Seemann, Composition Root, 2011

Cheney, 2016: the Go reading. "All things being equal the import graph of a well designed Go program should be a wide, and relatively flat, rather than tall and narrow." DIP "encourages you to push the responsibility for the specifics, as high as possible up the import graph, to your main package or top level handler".

BeforeCheckoutServicepolicyPostgresOrderRepodatabase/sql, SQL textimport and call both point down:policy changes when storage changesAfter: package after (policy owns the port)CheckoutServiceinterface OrderRepositorypostgresOrderRepomemoryOrderRepo (fake)main / composition root: picks one, injects itimportsimplementsimplements

The left half of the diagram is the traditional shape: CheckoutService imports the Postgres repository, so both the import and the call point down. On the right, the interface lives in the policy's package, both adapters point up at it, and only the composition root at the bottom knows which one is used.

The concepts, one by one ​

Direction of dependency Must-know ​

In plain words: draw an arrow from every file to every file it imports. DIP says arrows should point from details (SQL, HTTP, SDKs) toward policy, never from policy toward details.

Common misunderstanding: "My service calls an interface, so it's inverted." Not if the interface is declared in the postgres package: the service still imports postgres.

Definition: module A depends on module B if A's source mentions a name declared in B (import, use, type hint). DIP constrains these source dependencies; control flow is free to go the other way.

text
     Request flow (run time)                         Source dependencies (compile time)
1    HTTP handler -> CheckoutService.Complete         handler imports checkout
2    CheckoutService -> repo.MarkPaid                 checkout imports nothing about storage
3    postgres.OrderRepo.MarkPaid -> UPDATE orders     postgres satisfies checkout's interface
4    -- control goes down; the import from postgres to checkout's abstraction points up (Go: implicitly)

Real scenarios: an order service whose domain package imports github.com/stripe/stripe-go; a Laravel action that type-hints Illuminate\Http\Request in domain code; a domain entity extending Illuminate\Database\Eloquent\Model (a pragmatic choice in Laravel, but a dependency on the framework); a Go billing package importing net/http to call a partner API directly.

LanguageHow you see the arrowsTool
Gogo list -f with an .ImportPath / .Imports template (exact command in the lab)go list, goda, import cycle errors
PHP / Laraveluse statements and type hintsDeptrac, PHPStan rules, composer why
Javaimport, module requiresArchUnit, JPMS modules
C#using, project referencesNetArchTest, project reference graph
TypeScriptimportdependency-cruiser, ESLint import/no-restricted-paths, Nx boundaries
Pythonimportimport-linter

Fix: move the interface into the policy package and let the adapter satisfy it; then enforce the direction with the tool in the table so it cannot regress.

Ownership of the abstraction Must-know ​

In plain words: whoever needs the behaviour writes the interface, in their own words. The supplier adapts to it.

Common misunderstanding: "StripeGatewayInterface next to StripeGateway is an abstraction." It is a header interface for one vendor; its methods speak Stripe (createPaymentIntent, PaymentIntent objects), and it lives in the vendor adapter's namespace.

Definition: Martin's part B: "Abstractions should not depend upon details." An owned abstraction uses the domain's types (Order, Money, PaymentReference), lives in the domain or application layer, and contains only what the policy calls. Go's guideline matches it: interfaces "generally belong in the package that uses values of the interface type".

text
     Vendor-owned (not inverted)                      Policy-owned (inverted)
1    App\Payments\Stripe\StripeClientInterface        App\Checkout\Contracts\PaymentGateway
2    createPaymentIntent(array $params): PaymentIntent charge(Order $o): PaymentReference
3    domain imports App\Payments\Stripe\...           Stripe adapter imports App\Checkout\Contracts
4    switching to Adyen: domain changes               switching to Adyen: new adapter, one binding

Real scenarios: a Clock interface owned by the scheduling domain instead of calling time.Now() or now(); a Notifier owned by the ordering module rather than a mail SDK interface; a FeatureFlags port owned by the app with LaunchDarkly or Laravel Pennant behind it.

Fix: rename and move: put the interface in the policy's namespace or package, express it in domain types, and translate vendor types in the adapter.

Dependency inversion vs injection vs IoC vs container Must-know ​

In plain words: inversion is the shape (who depends on whom); injection is how an object receives its collaborators; IoC is the general idea that a framework calls you; a container is a tool that performs injection automatically.

Common misunderstanding: "We use Laravel's container, so we follow DIP." The container will happily inject a concrete StripeGateway into domain code. Injection without inversion is just a fancier new.

Definition: Fowler (2004): IoC is the generic phenomenon of frameworks; Dependency Injection is the specific pattern where "a separate assembler module" injects the implementation. A container automates the assembler using registrations and reflection (auto-wiring or autowiring: resolving constructor parameters by type).

text
1    DIP without DI:    policy owns interface; a factory inside the policy picks the adapter (still coupled)
2    DI without DIP:    container injects concrete PostgresOrderRepo into CheckoutService
3    DIP + manual DI:   main() builds postgres.OrderRepo and passes it to after.NewCheckoutService  (Go)
4    DIP + container:   #[Bind(StripeGateway::class)] interface PaymentGateway; constructor type-hints PaymentGateway (Laravel)
MechanismLaravel 13GoSpringASP.NET CoreNestJS
ContainerService container (PSR-11 compatible)None in stdlib; google/wire (code generation), uber-go/fx (runtime)ApplicationContextIServiceCollection / IServiceProviderModule injector
Auto-wiringYes, by type hint, "zero configuration resolution"No (explicit constructors)Yes (@Autowired, single-constructor injection)Yes (constructor)Yes (@Injectable(), by type)
Interface → implementationbind, #[Bind]Assignment in main@Primary, @Qualifier, profilesAddScoped<IFoo, Foo>(){ provide: TOKEN, useClass }

Fix: design the shape first (who owns which interface), then pick manual wiring or a container to realise it.

Injection styles Important ​

In plain words: the four ways an object can receive a dependency: through its constructor, a setter, a method argument, or an injector interface it implements.

Common misunderstanding: "Setter injection is more flexible." It also lets the object exist half-built. Spring's documentation: "it is a good rule of thumb to use constructors for mandatory dependencies and setter methods or configuration methods for optional dependencies", and "The Spring team generally advocates constructor injection".

Definition:

StyleHowUse forRisk
Constructor injectionDependencies are constructor parametersMandatory collaborators (default)Long constructors reveal too many responsibilities (a useful signal)
Setter (property) injectionsetLogger($l) after constructionOptional collaborators with defaultsTemporal coupling; object usable before it is complete
Method (parameter) injectionPass per call: handle(Order $o, Clock $clock)Per-call context; Laravel controller and job handle() methodsCallers must supply it every time
Interface injectionObject implements InjectFinder; injector calls itHistoric (Avalon); rare todayFramework coupling
text
1    Laravel resolves OrderController::__construct(PaymentGateway $g)    -- constructor injection
2    Laravel calls ProcessPayment::handle(PaymentGateway $g)             -- method injection on queued jobs
3    $logger->setFormatter($fmt)                                         -- setter injection (optional)
4    Go: svc := checkout.NewService(repo, clock)                         -- constructor function

Real scenarios: Laravel controllers (constructor and method injection), queued jobs (handle() method injection), Livewire components (boot() method injection); Go constructor functions NewX(deps...); PSR-3's LoggerAwareInterface::setLogger() (setter injection for an optional logger).

Fix: constructor injection by default; method injection for per-call values; setter only for truly optional collaborators with a safe default.

Composition root Must-know ​

In plain words: one place, at the program's entry point, where concrete types are chosen and connected. Everything else just declares what it needs.

Common misunderstanding: "Each module should register its own dependencies." Seemann: "Only applications should have Composition Roots. Libraries and frameworks shouldn't," and "A DI Container should only be referenced from the Composition Root."

Definition: Seemann: "a (preferably) unique location in an application where modules are composed together". In Go it is main (or a cmd/x/wire.go); in Laravel it is the service providers' register() methods plus #[Bind] attributes and bootstrap/app.php; in Spring the @Configuration classes; in .NET Program.cs.

text
     cmd/api/main.go (composition root)
1    db  := sql.Open("pgx", dsn)
2    repo := postgres.OrderRepo{DB: db}
3    svc := after.NewCheckoutService(repo)
4    http.Handle("/checkout", handlers.Checkout(svc))
     -- no package below main imports postgres and handlers together

Real scenarios: a Go service with cmd/api and cmd/worker, each a different composition of the same packages; a Laravel app whose AppServiceProvider binds PaymentGateway differently in testing; an integration test that builds its own composition with fakes.

Fix: move every new ConcreteThing, sql.Open, config('...') read and container call out of business code into the root.

Service locator: the anti-pattern Important ​

In plain words: instead of declaring dependencies, the object asks a global registry for them while running. It works, and it hides what the object needs.

Common misunderstanding: "Calling app(PaymentGateway::class) inside a class is dependency injection because the container is involved." It is service location: the dependency is invisible in the constructor and fails only at run time if unbound.

Definition: Seemann's summary of the problem: "it hides a class' dependencies, causing run-time errors instead of compile-time errors, as well as making the code more difficult to maintain because it becomes unclear when you would be introducing a breaking change." PSR-11 itself warns:

"Users SHOULD NOT pass a container into an object so that the object can retrieve its own dependencies." — PHP-FIG, PSR-11: Container interface

text
     class OrderProcessor { public function process($o) {            Consumer
1      $gw = app(PaymentGateway::class);                              new OrderProcessor()  -- constructor says "no dependencies"
2      $gw->charge($o); } }                                           ->process($order)
3                                                                     BindingResolutionException: Target [App\Contracts\PaymentGateway] is not instantiable.

Real scenarios: Laravel app()->make(), resolve() and App::make() inside domain classes; facades (Cache::get()) deep in domain logic (a static service locator with good test helpers); Go packages with a global var registry = map[string]any{}; Java ApplicationContext.getBean() calls in services.

Laravel featureLocator or injection?Where it is fine
Constructor type hintInjectionEverywhere
handle() / controller method type hintMethod injectionJobs, listeners, controllers
app()->make(), resolve(), App::make()Service locatorComposition root, factories, framework glue
Facades (Cache::, Mail::)Static service locator with swap supportControllers, routes, small apps; the docs say "most applications can use facades without issue"
Real-time facades (use Facades\App\...)Service locatorPrototyping
Contextual attributes (#[Config], #[Storage])InjectionConstructors

Fix: move the lookup into the constructor's type hints; keep container calls in providers and factories. Laravel's contracts documentation states the trade-off: "Unlike facades, which do not require you to require them in your class' constructor, contracts allow you to define explicit dependencies for your classes."

Ports and adapters, Clean Architecture and the dependency rule Must-know ​

In plain words: draw the business core in the middle; everything technical (web, database, broker, vendors) is an adapter at the edge plugged into a port the core defines; all imports point inward.

Common misunderstanding: "Hexagonal architecture means many folders and layers." It means one rule about dependencies. A small service can follow it with three packages: domain, adapters, cmd.

Definition: Cockburn: a port is a purpose-shaped interface of the application; an adapter converts between a technology and that port. Driving (primary) adapters call the application (HTTP controller, CLI, queue consumer); driven (secondary) adapters are called by it through ports it owns (repository, payment gateway, event publisher). Martin's Clean Architecture adds named rings (entities, use cases, interface adapters, frameworks and drivers) and the Dependency Rule quoted above; it promises a core "Independent of Database. You can swap out Oracle or SQL Server, for Mongo, BigTable, CouchDB, or something else."

text
     HTTP POST /orders ─▶ OrderController (driving adapter)
1      ─▶ PlaceOrder use case (port: PlaceOrderInput)
2      ─▶ OrderRepository port ─▶ PostgresOrderRepository (driven adapter) ─▶ PostgreSQL
3      ─▶ PaymentGateway port  ─▶ StripeGateway (driven adapter) ─▶ Stripe API
4      ─▶ EventPublisher port  ─▶ KafkaPublisher (driven adapter) ─▶ Kafka
     every import above points toward PlaceOrder and its ports
Application (hexagon)use cases + portsDomain entitiesno framework, no SQLdriving portPlaceOrderdriven portsOrderRepositoryPaymentGatewayEventPublisherHTTP controllerCLI / artisanQueue workerPostgreSQL repoStripe gatewayKafka publisherevery source dependency points inward; control flows in from the left and out to the right

The hexagon shows both kinds of adapter: driving adapters on the left call the use case through a driving port; driven adapters on the right implement ports the application owns. Every arrow is a source dependency, and all of them point inward.

Real scenarios: a Go service with internal/order (domain + ports), internal/postgres, internal/httpapi, cmd/api; a Laravel app with app/Domain/Orders containing contracts and actions, and app/Infrastructure containing Eloquent repositories and HTTP clients; replacing MySQL with PostgreSQL by writing one adapter.

Fix: enforce the rule mechanically: Go internal/ packages plus go list checks, Deptrac layers in PHP, ArchUnit in Java.

Stable abstractions and package metrics Good to know ​

In plain words: packages that many others depend on are hard to change (stable), so they should be abstract (interfaces) to remain extensible; packages that depend on many others and are depended on by none (adapters, main) are easy to change and should be concrete.

Common misunderstanding: "Stable means good." A stable concrete package (a shared models or utils package every service imports) is rigid: Martin calls the (0,0) corner of his chart undesirable, and his later books call it the zone of pain; an abstract package nobody uses, near (1,1), is the zone of uselessness.

Definition: from Martin's 1994 paper: Ca (afferent couplings) "The number of classes outside this category that depend upon classes within this category"; Ce (efferent couplings) the number inside that depend on classes outside; instability I = Ce / (Ca + Ce), where "I=0 indicates a maximally stable category"; abstractness A = abstract classes / total classes; the main sequence is the line from (0,1) to (1,0); distance D = |A + I − 1| / √2 (the paper also gives the normalised Dn = |A + I − 1|). The Stable Dependencies Principle (depend in the direction of stability) and Stable Abstractions Principle (a package should be as abstract as it is stable) are Martin's later names for these rules.

text
     Package            Ca  Ce   I = Ce/(Ca+Ce)   A     D'=|A+I-1|
1    checkout/ports     6   0    0.00             1.00  0.00   on the main sequence (stable, abstract)
2    checkout (domain)  3   1    0.25             0.40  0.35
3    postgres adapter   1   4    0.80             0.00  0.20
4    shared "models"    9   0    0.00             0.00  1.00   zone of pain: everyone imports a concrete package
Abstractness A = Na / NcInstability I = Ce / (Ca + Ce)101zone ofpainzone ofuselessnessmain sequenceReading the chartCa: packages outside that depend on this oneCe: packages outside this one that it depends onI = 0: maximally stable (everyone imports it)I = 1: maximally unstable (imports, nobody imports it)D = |A + I - 1| / √2, normalised Dn = |A + I - 1|• (0,1) contracts / ports package: stable, abstract• middle: domain and use cases• (1,0) adapters and main: unstable, concrete• red dot: shared "utils" or a concretemodel package every service importsStable Dependencies: depend toward lower IStable Abstractions: the lower I, the higher A

The chart places each package by its instability (x) and abstractness (y). Contracts belong top-left, adapters and main bottom-right, and the domain somewhere along the dashed main sequence; the red dot is the shared concrete package that makes every change expensive.

Fix: keep stable packages abstract (ports, contracts, events schemas), and keep concrete code in unstable leaf packages. In Go, compute Ca/Ce from go list output (see the lab); in PHP, PhpMetrics and PHP Depend report instability and abstractness per namespace.

Over-abstraction: when inversion costs more than it returns Important ​

In plain words: every interface is a hop for readers and a file to maintain. Invert at seams where a second implementation exists or is needed for tests; leave the rest concrete.

Common misunderstanding: "Every class needs an interface for testability." Many classes are pure logic (no I/O) and are tested directly; others have exactly one implementation forever (your own PriceCalculator).

Definition: over-abstraction is an abstraction with one implementation, no test double and no expected variation; it adds indirection without decoupling anything. The Go wiki: "Do not define interfaces before they are used". Pike: "A little copying is better than a little dependency."

text
1    OrderServiceInterface -> OrderService (1 impl, never faked)       -- remove the interface
2    PriceCalculator (pure function of inputs)                          -- test directly, no interface
3    PaymentGateway (Stripe, Adyen, Fake)                               -- keep: real variation + test double
4    Clock (system clock, frozen clock in tests)                        -- keep: tiny, needed for tests

Real scenarios: an IUserService/UserService pair for every class in a .NET or Laravel codebase; Go packages exporting an interface for every struct; repositories wrapping Eloquent with methods that are one-line pass-throughs.

Fix: abstractions at I/O boundaries and at points of real variation; concrete, final classes elsewhere. Add the interface when the second implementation (or the fake) arrives.

Per-language and framework behaviour ​

ConcernGoLaravel 13Spring (Java)ASP.NET Core (C#)NestJS (TypeScript)Python
Typical wiringManual in main; wire or fx for large graphsService container, auto-wiring by type hintApplicationContext, component scanningIServiceCollection in Program.csModule providersManual; FastAPI Depends; libraries such as dependency-injector
Bind interface → classAssign concrete value to interface-typed parambind, singleton, scoped, #[Bind], #[Singleton], #[Scoped]@Component + @Primary / @QualifierAddTransient/AddScoped/AddSingleton<I, T>(){ provide, useClass/useValue/useFactory }Constructor args; FastAPI app.dependency_overrides
LifetimesWhatever main holdsPer resolve (bind), process (singleton), request/job (scoped)singleton (default), prototype, request, sessionTransient, Scoped, SingletonDefault singleton, request, transientManual
Per-consumer implementationPass different valuesContextual binding when()->needs()->give(), #[Give]@QualifierKeyed servicesInjection tokensManual
Config valuesStruct fields filled in main#[Config('key')], giveConfig()@Value("${key}")IOptions<T>ConfigServiceSettings objects
Interface owned by consumerNatural (implicit interfaces)Convention (App\Contracts)ConventionConventionConvention (injection tokens for interfaces, which are erased at run time)Protocol in consumer module
Locator escape hatchGlobal varsapp(), resolve(), facadesgetBean()IServiceProvider.GetServiceModuleRef.get()Globals

Go ​

Before ​

The checkout policy imports database/sql, knows the table name and constructs its own Postgres repository. You cannot test Complete without a database, and a storage change is a change to the business package.

go
package before

import (
	"context"
	"database/sql"
)

// The business rule lives here, yet the package imports database/sql and
// builds its own Postgres repository. The policy depends on the detail.
type PostgresOrderRepo struct{ DB *sql.DB }

func (r PostgresOrderRepo) MarkPaid(ctx context.Context, id string) error {
	_, err := r.DB.ExecContext(ctx, `UPDATE orders SET status='paid' WHERE id=$1`, id)
	return err
}

type CheckoutService struct {
	repo PostgresOrderRepo // concrete type, concrete database
}

func NewCheckoutService(db *sql.DB) *CheckoutService {
	return &CheckoutService{repo: PostgresOrderRepo{DB: db}}
}

func (s *CheckoutService) Complete(ctx context.Context, orderID string) error {
	// ...charge the customer...
	return s.repo.MarkPaid(ctx, orderID)
}

After ​

The policy package defines the OrderRepository interface it needs and imports nothing about storage.

go
// Package after holds the high-level policy. It owns the abstraction it needs
// and imports nothing about databases.
package after

import "context"

// OrderRepository is defined here, next to the code that uses it.
// Low-level packages will depend on this interface, not the other way round.
type OrderRepository interface {
	MarkPaid(ctx context.Context, id string) error
}

type CheckoutService struct {
	repo OrderRepository
}

func NewCheckoutService(repo OrderRepository) *CheckoutService {
	return &CheckoutService{repo: repo}
}

func (s *CheckoutService) Complete(ctx context.Context, orderID string) error {
	// ...charge the customer...
	return s.repo.MarkPaid(ctx, orderID)
}

The Postgres package is a detail. It is the only place that knows SQL exists; thanks to Go's implicit interfaces it does not even import the policy package, yet it satisfies its interface.

go
// Package postgres is a detail. It depends on the abstraction, and it is
// the only place that knows SQL exists.
package postgres

import (
	"context"
	"database/sql"
)

type OrderRepo struct{ DB *sql.DB }

func (r OrderRepo) MarkPaid(ctx context.Context, id string) error {
	_, err := r.DB.ExecContext(ctx, `UPDATE orders SET status='paid' WHERE id=$1`, id)
	return err
}

A second detail behind the same port, for tests and local runs:

go
// Package memory is a second detail behind the same abstraction: an
// in-memory repository for tests, demos and local development.
package memory

import (
	"context"
	"fmt"
	"sync"
)

type OrderRepo struct {
	mu   sync.Mutex
	Paid []string
}

func (r *OrderRepo) MarkPaid(_ context.Context, id string) error {
	r.mu.Lock()
	defer r.mu.Unlock()
	if id == "" {
		return fmt.Errorf("memory: empty order id")
	}
	r.Paid = append(r.Paid, id)
	return nil
}

Wiring happens at the top of the import graph. The fake in main_wiring.go shows what tests pass:

go
package after

import "context"

// Wiring belongs at the top of the import graph: main (or a composition root)
// picks the concrete repository and hands it down. In a real program this
// lives in package main:
//
//	db, _ := sql.Open("pgx", dsn)
//	svc := after.NewCheckoutService(postgres.OrderRepo{DB: db})
//
// Tests pass a fake instead, with no database at all.
type fakeRepo struct{ paid []string }

func (f *fakeRepo) MarkPaid(_ context.Context, id string) error {
	f.paid = append(f.paid, id)
	return nil
}

var _ OrderRepository = (*fakeRepo)(nil)

And a runnable composition root that wires both details:

go
// Command kata is a composition root: the only place that names concrete
// types. Everything below it depends on after.OrderRepository.
package main

import (
	"context"
	"database/sql"
	"fmt"
	"os"

	"academy/solid/dip/after"
	"academy/solid/dip/after/memory"
	"academy/solid/dip/after/postgres"
)

func main() {
	ctx := context.Background()

	// Detail 1: in-memory, no infrastructure at all.
	mem := &memory.OrderRepo{}
	if err := after.NewCheckoutService(mem).Complete(ctx, "ord-1"); err != nil {
		fmt.Println("memory error:", err)
	}
	fmt.Println("memory paid:", mem.Paid)

	// Detail 2: PostgreSQL. The policy is identical; only the wiring differs.
	// No driver is imported in this kata, so Open fails: the failure is in
	// the composition root, never in the policy package.
	db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
	if err != nil {
		fmt.Println("postgres wiring:", err)
		return
	}
	_ = after.NewCheckoutService(postgres.OrderRepo{DB: db}).Complete(ctx, "ord-2")
}

The adapter's SQL and its error translation ​

The adapter is also where engine-specific behaviour is translated into the port's language. With PostgreSQL:

sql
-- postgres.OrderRepo.MarkPaid: idempotent, and reports "not found" distinctly.
UPDATE orders
SET    status = 'paid', paid_at = now()
WHERE  id = $1 AND status IN ('pending', 'paid')
RETURNING id;
-- 0 rows: the order does not exist or is cancelled -> adapter returns checkout.ErrOrderNotPayable
-- MySQL has no RETURNING on UPDATE: check RowsAffected() instead (and note InnoDB reports
-- 0 affected rows when the value is unchanged unless CLIENT_FOUND_ROWS is set).
go
func (r OrderRepo) MarkPaid(ctx context.Context, id string) error {
	var got string
	err := r.DB.QueryRowContext(ctx,
		`UPDATE orders SET status='paid', paid_at=now()
		 WHERE id=$1 AND status IN ('pending','paid') RETURNING id`, id).Scan(&got)
	if errors.Is(err, sql.ErrNoRows) {
		return checkout.ErrOrderNotPayable // the port's error, not the driver's
	}
	return err
}

The Go angle ​

Cheney reads DIP as a statement about the import graph. Go forbids import cycles, so the graph is acyclic, and DIP tells you its shape: wide and flat, with concrete choices pushed up to main. Two Go habits follow: define interfaces where they are consumed, in the package that uses them (the Go wiki rule), and keep main as the only package that knows which concrete types exist. Go's structural typing makes inversion cheaper than in nominal languages: the detail package satisfies the policy's interface without importing it, so the dependency arrow exists only at the composition root. The standard library is built this way: database/sql depends on the database/sql/driver interfaces it owns, and each driver (pgx, go-sql-driver/mysql, modernc.org/sqlite) depends on them and registers itself; net/http owns http.Handler, and every router and middleware depends on it. For large graphs, google/wire generates the wiring code at compile time and uber-go/fx resolves it at run time; most services are better served by a readable main.

Laravel ​

Before ​

The checkout service constructs its own Stripe gateway. Policy and detail are welded together; the only way to test it is to call Stripe.

php
<?php

namespace App\Services;

use App\Models\Order;
use App\Payments\StripeGateway;

// High-level policy (what it means to complete a checkout) is welded
// to a low-level detail (Stripe). You cannot test this without Stripe,
// and you cannot switch providers without editing the policy.
final class CheckoutService
{
    private StripeGateway $gateway;

    public function __construct()
    {
        $this->gateway = new StripeGateway(config('services.stripe.secret'));
    }

    public function complete(Order $order): void
    {
        $reference = $this->gateway->charge($order);
        $order->update(['status' => 'paid', 'payment_ref' => $reference]);
    }
}

After ​

A PaymentGateway contract owned by the application, a service that depends only on the contract, and a Stripe class that depends on the contract too. The #[Bind] attribute lets the interface declare its default implementation and a different one for local and testing, so the container resolves the right detail without a service provider entry; #[Config] injects the secret.

php
<?php

// app/Contracts/PaymentGateway.php — the abstraction, owned by the policy side.
// With the #[Bind] attribute (Laravel 13 container docs) the interface declares its default implementation.
namespace App\Contracts;

use App\Models\Order;
use App\Payments\FakeGateway;
use App\Payments\StripeGateway;
use Illuminate\Container\Attributes\Bind;

#[Bind(StripeGateway::class)]
#[Bind(FakeGateway::class, environments: ['local', 'testing'])]
interface PaymentGateway
{
    public function charge(Order $order): string;
}

// app/Services/CheckoutService.php — depends on the abstraction only.
namespace App\Services;

use App\Contracts\PaymentGateway;
use App\Models\Order;

final class CheckoutService
{
    public function __construct(private PaymentGateway $gateway) {}

    public function complete(Order $order): void
    {
        $reference = $this->gateway->charge($order);
        $order->update(['status' => 'paid', 'payment_ref' => $reference]);
    }
}

// app/Payments/StripeGateway.php — the detail depends on the abstraction.
namespace App\Payments;

use App\Contracts\PaymentGateway;
use App\Models\Order;
use Illuminate\Container\Attributes\Config;

final class StripeGateway implements PaymentGateway
{
    // The container injects the config value, so the interface can name this
    // class as its default implementation without a factory closure.
    public function __construct(#[Config('services.stripe.secret')] private string $secret) {}

    public function charge(Order $order): string
    {
        return (new \Stripe\StripeClient($this->secret))
            ->paymentIntents->create(['amount' => $order->total_cents, 'currency' => 'usd'])->id;
    }
}

// Without the attribute, the same wiring lives in a service provider:
//
//   $this->app->bind(PaymentGateway::class, StripeGateway::class);
//
// Or contextually, when two consumers need different details:
//
//   $this->app->when(RefundService::class)
//       ->needs(PaymentGateway::class)
//       ->give(StripeGateway::class);

Every binding style in one provider ​

php
<?php

namespace App\Providers;

use App\Contracts\Clock;
use App\Contracts\PaymentGateway;
use App\Infrastructure\{FrozenClock, SystemClock, StripeGateway, AdyenGateway};
use App\Services\{CheckoutService, RefundService, TenantContext};
use Illuminate\Support\ServiceProvider;

final class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // New instance on every resolve.
        $this->app->bind(PaymentGateway::class, StripeGateway::class);

        // One instance for the process lifetime (careful under Octane: never hold request state).
        $this->app->singleton(Clock::class, SystemClock::class);

        // One instance per request or job; flushed when Octane or a queue worker starts the next one.
        $this->app->scoped(TenantContext::class);

        // Contextual binding: RefundService gets Adyen, everyone else gets Stripe.
        $this->app->when(RefundService::class)
            ->needs(PaymentGateway::class)
            ->give(AdyenGateway::class);

        // Contextual primitive from configuration.
        $this->app->when(CheckoutService::class)
            ->needs('$currency')
            ->giveConfig('shop.currency');

        if ($this->app->environment('testing')) {
            $this->app->instance(Clock::class, new FrozenClock('2026-11-25 10:00:00'));
        }
    }
}

The same choices can live on the classes themselves with attributes Laravel 13 documents: #[Bind(StripeGateway::class)] and #[Bind(FakeGateway::class, environments: ['local', 'testing'])] on the interface, #[Singleton] or #[Scoped] on a class, and contextual attributes on constructor parameters: #[Config('app.timezone')], #[Storage('s3')], #[DB('mysql')], #[Cache('redis')], #[Log('daily')], #[Give(DatabaseRepository::class)], #[Tag('reports')].

The Laravel angle ​

The service container exists for this principle. Its documentation's definition of DI is the plain one: class dependencies are "injected" into the class via the constructor or, in some cases, "setter" methods. Auto-wiring ("zero configuration resolution") means concrete classes with no interface dependencies need no registration; you register only the seams: interface → implementation (bind, singleton, scoped, #[Bind]), per-consumer variations (contextual binding, #[Give]) and configuration (#[Config], giveConfig). Laravel's own Illuminate\Contracts package is DIP applied to a framework: Cache\Repository, Queue\Queue, Mail\Mailer, Filesystem\Filesystem are the abstractions; the Redis, SQS, SMTP and S3 drivers are details behind them. The container also implements PSR-11 ("you may type-hint the PSR-11 container interface to obtain an instance of the Laravel container"), which is useful for framework-agnostic packages and dangerous in domain code (that is the service locator). Octane changes one rule: a singleton lives across requests, so anything holding the request, the authenticated user or tenant state must be scoped or resolved per request.

Mechanics ​

Import cycles: why Go forces the question Must-know ​

When two packages need each other, Go refuses to build. The error, from a two-package repro (billing imports orders, orders imports billing):

text
package cyc/billing
	imports cyc/orders from b.go
	imports cyc/billing from o.go: import cycle not allowed

DIP is the standard fix: the package that holds the policy declares an interface for what it needs from the other, and the other side's concrete type satisfies it; the composition root connects them. PHP, Java and TypeScript allow cycles at the namespace level, so the same problem shows up later as untestable, tangled modules; tools like Deptrac or ArchUnit make it a build failure.

How a container resolves a constructor Important ​

text
     $app->make(CheckoutService::class)
1    reflection: __construct(PaymentGateway $gateway, Clock $clock, string $currency)
2    PaymentGateway: contextual binding for CheckoutService? no -> #[Bind]/bind() -> StripeGateway
3      StripeGateway::__construct(#[Config('services.stripe.secret')] string $secret) -> config value
4    Clock: singleton -> cached instance
5    string $currency: contextual giveConfig('shop.currency') -> 'EUR'
6    no binding and not instantiable (interface) -> BindingResolutionException: Target [X] is not instantiable.
LifetimeLaravelSpringASP.NET CoreNestJSPitfall
New per resolvebindprototype scopeAddTransientScope.TRANSIENTExpensive objects rebuilt often
Per request / jobscopedrequest scopeAddScopedScope.REQUESTInjecting into a singleton captures one request's instance (.NET validates "Scoped services aren't injected into singletons")
Process-widesingleton, #[Singleton]singleton (default)AddSingletonDefaultState leaks between requests under Octane, FPM workers reuse nothing, Go servers share everything

Measuring stability in practice Good to know ​

For each package, count Ca (who imports me) and Ce (whom I import) within your module, compute I = Ce / (Ca + Ce), and check the rule "depend toward lower I". A dependency from a package with I=0.2 onto one with I=0.8 is a Stable Dependencies violation: a volatile package can now break a stable one. In Go the data is one command away (see the lab); in PHP use PhpMetrics or PHP Depend; in Java JDepend (which computes Ca, Ce, I, A and D per package), in .NET NDepend.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Vendor SDK called from domain codePort + adapterPaymentGateway in domain; StripeGateway adapterSwap vendors; fake in testsAdapter maps types both ways
new of infrastructure inside servicesConstructor injectionType-hint the port; bind in provider or mainVisible dependenciesLonger constructors
Static calls (Cache::, time.Now()) in policyInject a port (Clock, Cache contract)Clock interface; frozen clock in testsDeterministic testsOne more parameter
Container calls in business codeMove to composition rootReplace app() with type hintsCompile-time visible graphRefactoring effort
Two packages import each otherInvert one edgeInterface in the policy packageCycle removedOne interface
Shared concrete models package across servicesConsumer-owned contracts / eventsEach service owns its read types; publish schemasServices deploy independentlyDuplication of DTOs ("a little copying")
Legacy or partner system with a foreign modelAnti-corruption layerTranslator owned by the consumerDomain model stays cleanExtra hop, mapping code
Framework types in the domain (Request, Model)Map at the edgeControllers build commands/DTOsDomain testable without HTTPMore mapping code
Interface for every classRemove one-implementation interfacesKeep only I/O seamsLess indirectionReintroduce when variation appears

Choosing ​

SituationRecommendedExtra techniqueReason
Business logic calling DB, HTTP, queue, clockInvert: port in the domain, adapter outsideContract tests on the adapter (LSP)Test without infrastructure, swap details
Pure computation (pricing rules, validation)No abstractionPlain unit testsNothing to invert
Go serviceManual wiring in maingo list checks in CIReadable, compile-time checked
Laravel appContainer with #[Bind] / providersContextual binding for per-consumer variantsFramework-native
Large Go graph (dozens of components)google/wire (compile time) or uber-go/fxKeep providers per packageGenerated wiring stays checked
Library or packageAccept dependencies via constructors; no containerOptional PSR-11 support at the edgeLibraries must not have composition roots
Many request-scoped services under Octanescoped bindingsOctane's flush configNo state leaks between requests
Integrating a foreign modelAnti-corruption layerConsumer-driven contractsKeep your language yours

In architecture: from a single process to a distributed system ​

Monolith: one process ​

The simplest correct usage: a domain/application layer that owns ports (OrderRepository, PaymentGateway, Clock), infrastructure classes implementing them, and one composition root. Example: a Laravel monolith with app/Domain/Checkout/Contracts/PaymentGateway.php, app/Infrastructure/Payments/StripeGateway.php, bindings via #[Bind], and Deptrac rules that fail the build if App\Domain uses Illuminate\Http or Stripe\.

Modular monolith and multiple databases ​

Modules depend on each other's published contracts, never on each other's Eloquent models or tables. The consuming module owns the interface it needs (Shipping owns OrderLookup), and the providing module supplies an adapter. Example: when Orders moves from MySQL to PostgreSQL (a second connection, #[DB('pgsql')] on its repository), Shipping is untouched because it depended on OrderLookup, not on App\Orders\Models\Order.

Microservices: consumer-owned contracts and anti-corruption layers ​

Across services there is no shared interface type, so DIP becomes a rule about who owns the contract. The consumer states what it needs (consumer-driven contracts, see LSP); the provider conforms. When the provider's model is foreign (a legacy ERP, a partner API), the consumer puts an anti-corruption layer in front of it. Microsoft's pattern description: "Isolate the different subsystems by placing an anti-corruption layer between them. This layer translates communication between the two systems." Eric Evans first described it in Domain-Driven Design.

text
1    checkout ──port: InventoryReservations.reserve(sku, qty)──▶ inventory-acl (owned by checkout team)
2    inventory-acl ──SOAP: ERP_RESERVE_STOCK(MATNR, MENGE, WERKS)──▶ legacy ERP
3    ERP fault "MATNR unknown" ──▶ inventory-acl ──▶ checkout.ErrUnknownProduct
4    checkout never imports ERP field names; ERP replacement = new ACL, same port

Events invert the same way: the publisher owns the event schema as a stable contract; consumers depend on the schema, not on the publisher's internals. A shared library of concrete domain models imported by every service is the distributed zone of pain.

Distributed data: replicas, caches and multi-region ​

Infrastructure topology is a detail behind ports. A UserReadModel port can be served by a PostgreSQL read replica today, a Redis cache tomorrow and a MongoDB or Elasticsearch projection later, without touching the use cases; the port's documentation states the consistency the use case may assume (fresh vs bounded staleness), and each adapter must honour it. Example: a CatalogSearch port implemented first with PostgreSQL full-text search, later with OpenSearch; the composition root switches by configuration, and the contract test suite runs against both. Engine-level guarantees are on Replication & Failover.

Scaling path: 1×, 10×, 100× ​

ScaleWhat DIP looks like
1×: one app, one teamPorts only at I/O seams; manual wiring or framework container; one composition root
10×: modules or a few servicesModule contracts owned by consumers; dependency rules enforced in CI (Deptrac, go list, ArchUnit); adapters swapped per environment
100×: many services and teamsConsumer-driven contracts, ACLs at every foreign boundary, schema registries for events, platform adapters (storage, messaging) behind team-owned ports; stability metrics tracked per package

Lab: refactoring kata ​

Outputs below were produced by running the code on this page with Go 1.27 (module declares go 1.24). PHP steps state the expected observation.

Setup.

bash
cd docs/snippets/solid/go
go vet ./dip/...   # clean

Step 1: read the import graph before and after.

bash
go list -f '{{.ImportPath}}: {{join .Imports " "}}' ./dip/...
# academy/solid/dip/after: context
# academy/solid/dip/after/memory: context fmt sync
# academy/solid/dip/after/postgres: context database/sql
# academy/solid/dip/before: context database/sql
# academy/solid/dip/kata: academy/solid/dip/after academy/solid/dip/after/memory academy/solid/dip/after/postgres context database/sql fmt os

Observation: before (the policy) imports database/sql; after imports only context. The only package that imports concrete adapters is kata, the composition root.

Step 2: run the composition root.

bash
go run ./dip/kata
# memory paid: [ord-1]
# postgres wiring: sql: unknown driver "pgx" (forgotten import?)

Observation: the policy ran unchanged with the in-memory detail. The Postgres wiring failed in the composition root because no driver is imported; add _ "github.com/jackc/pgx/v5/stdlib" and a DATABASE_URL to make it real. The policy package never changes.

Step 3: create and break an import cycle. Make two packages import each other:

bash
go build ./...
# package cyc/billing
# 	imports cyc/orders from b.go
# 	imports cyc/billing from o.go: import cycle not allowed

Fix it by declaring in billing an interface for what it needs from orders, deleting the import, and wiring both in main.

Step 4: compute instability. Count afferent and efferent couplings inside the module:

bash
go list -f '{{.ImportPath}} {{join .Imports " "}}' ./dip/... | awk '
  { for (i = 2; i <= NF; i++) if ($i ~ /^academy\//) { ce[$1]++; ca[$i]++ } pk[$1]=1 }
  END { for (p in pk) printf "%-40s Ca=%d Ce=%d I=%.2f\n", p, ca[p], ce[p], (ca[p]+ce[p]) ? ce[p]/(ca[p]+ce[p]) : 0 }' | sort
# academy/solid/dip/after                  Ca=1 Ce=0 I=0.00
# academy/solid/dip/after/memory           Ca=1 Ce=0 I=0.00
# academy/solid/dip/after/postgres         Ca=1 Ce=0 I=0.00
# academy/solid/dip/before                 Ca=0 Ce=0 I=0.00
# academy/solid/dip/kata                   Ca=0 Ce=3 I=1.00

Observation: the composition root is maximally unstable (I=1, nobody imports it), which is exactly right for the place that names concrete types. In Go, adapters satisfy the policy's interface implicitly, so their arrow to after does not show up as an import; add var _ after.OrderRepository = OrderRepo{} in postgres to make the dependency explicit and watch after's Ca grow.

Step 5 (Laravel): from new to the container. In a Laravel 13 app, start with Before.php. Expected: a feature test of CheckoutService::complete() calls Stripe (or fails without a key). Switch to After.php: with APP_ENV=testing the #[Bind(FakeGateway::class, environments: ['local', 'testing'])] attribute makes the container inject the fake, and the test runs offline. Remove the attribute and the provider binding: expected Illuminate\Contracts\Container\BindingResolutionException with "Target [App\Contracts\PaymentGateway] is not instantiable."

Step 6 (Laravel): replace a locator. Find app(...), resolve(...) or App::make(...) in a domain class, move the dependency to the constructor, and run php artisan test. Expected: same behaviour, and the dependency now appears in the constructor signature (and in static analysis).

Common misconceptions ​

BeliefReality
"DIP means using a DI container."Manual constructor wiring in main is DIP and DI; a container is optional tooling.
"Dependency injection is dependency inversion."Injection is a technique; inverting the graph and owning the abstraction is the principle.
"An interface next to the class inverts the dependency."If the policy imports the adapter's package to get it, nothing was inverted.
"Inversion reverses the call direction."Control still flows from policy to detail; only source dependencies and ownership change.
"Every class needs an interface."Only seams with real variation or a needed test double; the rest is over-abstraction.
"app()->make() in a service is fine because it uses the container."That is service location: hidden dependencies, run-time failures. PSR-11 advises against it.
"Facades are always an anti-pattern."They are a static locator with test swaps; Laravel's docs consider them fine in most applications, but keep them out of domain code you want framework-independent.
"Hexagonal architecture requires many layers."It requires one rule: dependencies point inward to ports the application owns.
"Stable packages are good packages."Stable concrete packages are rigid (zone of pain); stable packages should be abstract.
"Singletons are harmless in Laravel."Under Octane a singleton lives across requests; request or tenant state must be scoped.
"A shared models library keeps services consistent."It couples every service to one concrete package; prefer consumer-owned contracts and schemas.
"Libraries should register themselves in the container."Only applications have composition roots; libraries accept dependencies.

Cheat sheet ​

TopicWhat to remember
RuleHigh-level and low-level both depend on abstractions owned by the high level
Two inversionsDirection of source dependency; ownership of the interface
DIP / DI / IoC / containerPrinciple / technique / framework property / tool
Injection stylesConstructor (default), method (per call), setter (optional), interface (historic)
Composition rootOne place at the entry point; only place that names concrete types or calls the container
Service locatorHides dependencies; app()/resolve() only in the root
GoDefine interfaces where they are consumed; wiring in main; import cycles forbidden
Laravel bindingsbind, singleton, scoped, instance, when()->needs()->give(), #[Bind], #[Singleton], #[Scoped], #[Config], #[Give]
PSR-11get and has; "Users SHOULD NOT pass a container into an object"
Ports and adaptersDriving adapters call in; driven adapters implement ports the core owns
Dependency RuleSource dependencies point inward only (Clean Architecture)
MetricsI = Ce/(Ca+Ce), A = abstract/total, `Dn =
Across servicesConsumer-owned contracts, anti-corruption layers, owned event schemas
Over-abstractionNo interface without a second implementation or a fake

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What two things does DIP invert, and which one do people usually miss? Must-know ​

Answer

Answer: The direction of the source dependency and the ownership of the abstraction. Ownership is usually missed: an interface defined next to the vendor adapter inverts nothing.

2 — Does inversion change the run-time call direction? Important ​

Answer

Answer: No. The policy still calls the detail at run time; only compile-time dependencies (imports) point the other way.

3 — Distinguish dependency inversion, dependency injection, inversion of control and a DI container. Must-know ​

Answer

Answer: DIP is a principle about the dependency graph; DI is the technique of handing an object its collaborators; IoC is the general framework property of calling your code; a container is a tool that automates injection.

4 — Why is calling app(PaymentGateway::class) inside a domain service a problem? Important ​

Answer

Answer: It is a service locator: the dependency is hidden from the constructor, failures occur at run time (BindingResolutionException), and it is hard to tell when a change is breaking. PSR-11 advises against passing a container into objects.

5 — Where should Go interfaces be declared, and why does that help DIP? Must-know ​

Answer

Answer: In the package that uses them. The policy owns the abstraction, and implicit satisfaction means the adapter need not import the policy; concrete types are connected in main.

6 — What is a composition root and who should have one? Important ​

Answer

Answer: The single place at the application's entry point where concrete types are chosen and connected. Applications have one; libraries and frameworks should not.

7 — When would you use Laravel's scoped instead of singleton? Important ​

Answer

Answer: For services holding per-request or per-job state, so Octane workers and queue workers get a fresh instance per request/job instead of leaking state.

8 — What does contextual binding solve? Important ​

Answer

Answer: Two consumers of the same interface needing different implementations, e.g. RefundService gets Adyen while everyone else gets Stripe: when(RefundService::class)->needs(PaymentGateway::class)->give(AdyenGateway::class).

9 — Compute instability for a package with Ca=6 and Ce=2. Should it be abstract? Good to know ​

Answer

Answer: I = 2/(6+2) = 0.25, fairly stable. By the Stable Abstractions rule it should be fairly abstract (around A = 0.75 to be on the main sequence).

10 — How does DIP apply between microservices that share no interface types? Important ​

Answer

Answer: Through ownership of contracts: consumers own what they need (consumer-driven contracts), publishers own stable event schemas, and consumers wrap foreign models in an anti-corruption layer.

11 — When is adding an interface over-abstraction? Must-know ​

Answer

Answer: When it has one implementation, no test double and no expected variation, such as an interface over pure computation or a 1:1 mirror of a service class.

12 — Two Go packages import each other. What does the compiler say and how does DIP fix it? Must-know ​

Answer

Answer: "import cycle not allowed". Declare in one package an interface for what it needs from the other, remove that import, and wire the concrete type in main.

Glossary ​

TermMeaning
Dependency Inversion Principle (DIP)High-level and low-level modules depend on abstractions; abstractions do not depend on details
Direction of dependencyWhich module's source mentions which; DIP points it from details toward policy
Ownership (of an abstraction)The module that defines an interface in its own terms; should be the consumer/policy
Dependency injection (DI)Supplying an object's collaborators from outside
Inversion of control (IoC)Framework calls application code; "Hollywood Principle"
Hollywood Principle"Don't call us, we'll call you"
IoC container / DI containerLibrary that builds object graphs from registrations and reflection
Auto-wiring / autowiringResolving constructor parameters automatically by type
Composition rootSingle place where the application's object graph is composed
Constructor injectionDependencies passed as constructor parameters
Setter injectionDependencies set through methods after construction
Method injectionDependencies passed per method call (Laravel handle())
Interface injectionObject implements an injector interface the container calls
Service locatorObject fetches dependencies from a registry at run time; an anti-pattern in business code
Facade (Laravel)Static proxy to a container service; a locator with test helpers
Real-time facadeLaravel feature that turns any class into a facade via a Facades\ namespace prefix
PSR-11 / ContainerInterfacePHP-FIG standard container interface with get() and has()
bind / singleton / scopedLaravel lifetimes: per resolve, per process, per request/job
Contextual bindingLaravel when()->needs()->give(): different implementation per consumer
#[Bind], #[Singleton], #[Scoped]Laravel attributes declaring binding and lifetime on interfaces/classes
#[Config], #[Give]Laravel contextual attributes injecting config values or a specific implementation
OctaneLaravel's long-running application server; singletons persist across requests
Ports and adapters / hexagonal architectureCockburn's architecture: application ports, technology adapters
Driving / driven adapterAdapter that calls the application / adapter the application calls through a port
Clean ArchitectureMartin's 2012 concentric architecture with the Dependency Rule
Dependency RuleSource code dependencies can only point inwards
Import graph / import cyclePackage dependency graph; Go rejects cycles at build time
Afferent coupling (Ca)Number of outside classes depending on a package
Efferent coupling (Ce)Number of outside classes a package depends on
Instability (I)Ce / (Ca + Ce); 0 stable, 1 unstable
Abstractness (A)Share of abstract types in a package
Main sequenceLine A + I = 1 where abstractness balances stability
Zone of pain / zone of uselessnessStable concrete packages / abstract unused packages (Martin's later terms)
Stable Dependencies PrincipleDepend in the direction of stability
Stable Abstractions PrincipleA package should be as abstract as it is stable
Consumer-owned contractContract defined by what the consumer needs, verified against the provider
Anti-corruption layer (ACL)Consumer-owned translator isolating a domain from a foreign model (Evans)
Over-abstractionInterfaces with one implementation and no variation or test need
Wire / FxGo DI tools: compile-time code generation (google/wire), runtime container (uber-go/fx)
Spring / NestJSJava and TypeScript frameworks with built-in DI containers

References ​

Built by Morteza Negahi