.NET Hexagonal Architecture 学习笔记

Hexagonal Architecture


定义

Hexagonal Architecture ,即六边形结构,是一种将用例与外部细节分离的结构策略。

六角形建筑脱离了分层结构。可以在分层架构中使用依赖注入和其他技术来启用测试。但是在六边形模型中有一个关键的区别:UI也可以被交换掉。

Hexagonal architecture was proposed by Alistair Cockburn in 2005. “Hexagonal architecture” was actually the working name for the “ports and adapters pattern,” which is the term Alistair settled on in the end. But the “hexagonal architecture” name stuck, and that’s the name many people know it by today.


意图

背后的想法是将输入和输出放在结构设计的边缘。这样做,你将应用程序的中心逻辑(核心)与外部关注点隔离开来。并且允许应用程序由用户、程序或测试同等驱动,并在与其最终运行时设备和数据库隔离的情况下进行开发和测试。

解释:

1.外部细节(或外部关注点)

什么是外部细节?举个例子:界面,API等, 可以被mocked或faked,可以被替换为具体的实现的这一类

VisualStudio使我们可以在项目中添加反射、序列化、安全性和许多其他Nuget包的库。当我们将这些库添加到应用程序和域时,这些库都只是细节,也就是结构的接口和适配器,是六边形的边缘部分

Keep in mind the Uncle Bob’s quote:
A good architecture allows major decisions to be deferred and a good architect maximize the number of decisions not made.

2.业务规则和用例

业务规则封装了实体字段和条件,用例与许多实体和服务交互。
业务规则与用例一起在应用程序中创建出过程(process)

原理:DIP(Dependency Inversion Principle)

High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions.

  • DepositService 是高级模块这不依赖于数据库细节,而是依赖于IAccountRepository抽象。
  • IAccountRepository是抽象化它不依赖于数据库详细信息。
  • AccountSQLRepository是低层模块这取决于IAccountRepository抽象。

在这里插入图片描述

结构风格

  • 一个独立的业务域,它包含一小部分关键业务规则。
  • 应用程序服务(Service)来实现用例。
  • 端口(API)以获取输入。
  • 适配器提供框架的实现和对数据库的访问(Entity)。
  • 外部用户、其他系统和服务。

在这里插入图片描述

端口组件:
请求(DepositRequest.cs)
控制器+行动(DepositController.cs)
模型(Model.cs)

应用程序具有六角形,因为它的每一方都有具体的协议。
端口和适配器是作为插件在应用程序外部实现的。


不同层级的依赖关系

在这里插入图片描述

  • 域完全独立于其他层和框架。
  • 应用程序依赖于域,并且独立于框架、数据库和UI。
  • 适配器为应用程序需求提供实现。
  • UI依赖于应用程序,并通过间接加载基础设施。

参考资料

https://paulovich.net/hexagonal-architecture-dot-net/
https://codingcanvas.com/hexagonal-architecture/
https://blog.ndepend.com/hexagonal-architecture/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值