Onion Architecture
Onion architecture places the domain model at the centre and treats frameworks, databases, and UI as outer details, inverting dependencies toward the domain.
Definition
Onion architecture is a layered pattern in which the domain model forms the innermost circle and all dependencies point inward, so outer layers implement interfaces the domain defines.
Context and scope
It is chosen when business logic must stay independent of frameworks and testable without infrastructure.
Common misconceptions
- onion architecture means having many physical layers
- it forbids the domain from depending on any interface at all
Anti-patterns
- defining repository interfaces in the infrastructure layer
- letting ORM annotations into the domain model
Related concepts
Authoritative source
https://jeffreypalermo.com/2008/07/the-onion-architecture-part-1/
Definition
Onion architecture is a layered pattern in which the domain model forms the innermost circle and all dependencies point inward, so outer layers implement interfaces the domain defines.
It is chosen when business logic must stay independent of frameworks and testable without infrastructure. Compared to simpler alternatives, this concept fits best when the trade-off it represents is the one the system actually cares about.
When to use it
A common use case is applying it at the boundary where the cost of getting it wrong is highest, and the scenario usually involves a concrete guarantee the system must uphold. Unlike an ad hoc approach, it makes that guarantee explicit, reviewable, and testable.
How it works
Dependencies point inward through interfaces owned by the inner layers, so the domain declares what it needs and infrastructure provides implementations.
This inversion lets the domain be tested with in-memory implementations and lets a database or framework be replaced without touching business rules.
Trade-offs and alternatives
The cost is extra indirection and mapping between domain and persistence types, which some teams find outweighs the isolation for simple CRUD applications. The main drawback is the extra complexity it introduces, so the benefit should clearly outweigh that cost before a team adopts it.
Common misconceptions
A persistent misconception is that onion architecture means having many physical layers. Another is that it forbids the domain from depending on any interface at all. For example, an engineer who assumes otherwise may design around a guarantee that does not actually exist, which only becomes obvious under load or failure.
Anti-patterns to avoid
Two recurring anti-patterns are to defining repository interfaces in the infrastructure layer and to letting ORM annotations into the domain model. Both tend to surface as hard-to-debug production issues rather than obvious test failures. Related concepts include Clean Architecture, Domain-Driven Design, Bounded Context.