ASP.NET之六边形架构(Hexagonal Architecture)

六边形架构,也称为端口与适配器架构(Ports and Adapters Architecture),是一种软件设计模式,旨在创建松耦合、可测试和易于维护的应用程序。下面介绍如何在ASP.NET中实现六边形架构。

六边形架构核心概念

  1. 领域核心:位于架构中心,包含业务逻辑和领域模型

  2. 端口:定义应用程序与外部世界的交互接口

    • 主端口(驱动端口):API、UI等主动调用应用的入口

    • 次端口(被驱动端口):数据库、外部服务等应用需要调用的出口

  3. 适配器:实现端口与具体技术的转换

ASP.NET 六边形架构分层

典型的ASP.NET六边形架构包含以下层次:

[外部世界]
│
├── [基础设施层] (适配器)
│   ├── Web API适配器 (主适配器)
│   ├── 数据库适配器 (次适配器)
│   └── 外部服务适配器 (次适配器)
│
├── [应用层] (端口/接口)
│   ├── 控制器接口 (主端口)
│   ├── 仓储接口 (次端口)
│   └── 服务接口 (次端口)
│
└── [领域层] (核心)
    ├── 领域模型
    └── 领域服务

实现步骤

1. 创建领域层

// Domain/Entities/Product.cs
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

// Domain/Interfaces/IProductRepository.cs (次端口)
public interface IProductRepository
{
    Task GetByIdAsync(int id);
    Task AddAsync(Product product);
}

// Domain/Services/ProductService.cs
public class ProductService
{
    private readonly IProductRepository _repository;
    
    public ProductService(IProductRepository repository)
    {
        _repository = repository;
    }
    
    public async Task GetProduct(int id)
    {
        return await _repository.GetByIdAsync(id);
    }
}

2. 创建基础设施层

// Infrastructure/Repositories/ProductRepository.cs (次适配器)
public class ProductRepository : IProductRepository
{
    private readonly AppDbContext _context;
    
    public ProductRepository(AppDbContext context)
    {
        _context = context;
    }
    
    public async Task GetByIdAsync(int id)
    {
        return await _context.Products.FindAsync(id);
    }
    
    public async Task AddAsync(Product product)
    {
        await _context.Products.AddAsync(product);
        await _context.SaveChangesAsync();
    }
}

3. 创建Web API适配器 (主适配器)

// WebAPI/Controllers/ProductsController.cs
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly ProductService _productService;
    
    public ProductsController(ProductService productService)
    {
        _productService = productService;
    }
    
    [HttpGet("{id}")]
    public async Task Get(int id)
    {
        var product = await _productService.GetProduct(id);
        if (product == null) return NotFound();
        return Ok(product);
    }
}

4. 配置依赖注入

// Program.cs 或 Startup.cs
builder.Services.AddScoped();
builder.Services.AddScoped();

优势

  1. 可测试性:领域核心不依赖外部框架,易于单元测试

  2. 可替换性:通过更换适配器可以轻松切换数据库或UI框架

  3. 关注点分离:业务逻辑与技术实现分离

  4. 灵活性:适应需求变化和技术演进

在ASP.NET Core中的最佳实践

  1. 使用MediatR实现CQRS模式

  2. 使用AutoMapper处理DTO转换

  3. 使用FluentValidation进行输入验证

  4. 将应用层作为协调者,不包含业务逻辑

六边形架构特别适合复杂业务场景的ASP.NET应用程序,虽然初期需要更多设计工作,但长期来看能显著提高代码的可维护性和可扩展性。

你可能感兴趣的:(架构,asp.net)