← 中文资源

简体中文版本

洋葱架构

洋葱架构把领域模型置于中心,把框架、数据库与 UI 视为外层细节,使依赖指向领域并由领域定义接口。

阅读英文原文

概念概述

洋葱架构(Onion Architecture)指的是:洋葱架构把领域模型置于中心,把框架、数据库与 UI 视为外层细节,使依赖指向领域并由领域定义接口。

从更严格的定义看,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. 它与 Clean Architecture、Domain-Driven Design、Bounded Context 等概念经常一起出现,用于解决相近的工程问题。理解它的适用场景,有助于在多种备选方案之间做出有依据的取舍,而不是凭直觉选择技术方案。

常见误解

  • onion architecture means having many physical layers
  • it forbids the domain from depending on any interface at all

需要避免的反模式

  • defining repository interfaces in the infrastructure layer
  • letting ORM annotations into the domain model

实践要点

  1. Dependencies point inward through interfaces owned by the inner layers, so the domain declares what it needs and infrastructure provides implementations.
  2. This inversion lets the domain be tested with in-memory implementations and lets a database or framework be replaced without touching business rules.
  3. The cost is extra indirection and mapping between domain and persistence types, which some teams find outweighs the isolation for simple CRUD applications.

参考来源

https://jeffreypalermo.com/2008/07/the-onion-architecture-part-1/