位置: 文档库 > C#(.NET) > .net逻辑分层架构总结

.net逻辑分层架构总结

周传雄 上传于 2025-08-18 08:27

《.NET逻辑分层架构总结》

在.NET企业级应用开发中,逻辑分层架构是构建可维护、可扩展系统的核心设计模式。通过将业务逻辑、数据访问、表现层等分离,开发者能够更高效地管理代码复杂度,提升团队协作效率。本文将从基础分层模型出发,深入探讨.NET环境下分层架构的设计原则、实现细节及优化策略。

一、分层架构的核心价值

传统单体架构中,所有功能代码耦合在一个项目中,导致修改一处可能影响全局。分层架构通过物理或逻辑隔离,将系统划分为多个垂直模块,每个模块承担单一职责。例如,三层架构(表现层、业务逻辑层、数据访问层)是经典实现方式,其优势包括:

  • 解耦性:各层独立开发、测试与部署
  • 可维护性:修改某一层不影响其他层
  • 可扩展性:通过替换某一层实现技术升级(如从SQL Server迁移到MongoDB)
  • 团队协作:前后端开发者可并行工作

二、经典三层架构实现

1. 表现层(Presentation Layer)

负责用户交互,通常包含Web API、MVC控制器或Blazor组件。在ASP.NET Core中,控制器通过依赖注入获取业务服务:

// ASP.NET Core Web API 示例
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly IProductService _productService;

    public ProductsController(IProductService productService)
    {
        _productService = productService;
    }

    [HttpGet("{id}")]
    public async Task> Get(int id)
    {
        var product = await _productService.GetProductAsync(id);
        if (product == null) return NotFound();
        return Ok(product);
    }
}

2. 业务逻辑层(Business Logic Layer, BLL)

包含核心业务规则,如订单计算、权限验证等。建议使用领域驱动设计(DDD)中的领域服务:

// 领域服务示例
public class OrderService : IOrderService
{
    private readonly IOrderRepository _orderRepository;
    private readonly IInventoryService _inventoryService;

    public OrderService(IOrderRepository orderRepository, 
                       IInventoryService inventoryService)
    {
        _orderRepository = orderRepository;
        _inventoryService = inventoryService;
    }

    public async Task PlaceOrderAsync(OrderRequest request)
    {
        // 业务规则验证
        if (!request.Items.Any()) 
            throw new BusinessException("订单不能为空");

        // 调用其他服务
        var inventoryCheck = await _inventoryService.CheckStockAsync(request.Items);
        if (!inventoryCheck.IsAvailable)
            return OrderResult.Failed("库存不足");

        // 数据持久化
        var order = MapToOrderEntity(request);
        await _orderRepository.AddAsync(order);

        return OrderResult.Success(order.Id);
    }
}

3. 数据访问层(Data Access Layer, DAL)

负责与数据库交互,推荐使用Entity Framework Core或Dapper。仓储模式(Repository Pattern)可进一步抽象数据操作:

// 仓储接口示例
public interface IRepository where T : class
{
    Task GetByIdAsync(int id);
    Task AddAsync(T entity);
    Task UpdateAsync(T entity);
    Task DeleteAsync(int id);
    Task> GetAllAsync();
}

// EF Core 实现
public class EfCoreRepository : IRepository where T : class
{
    private readonly DbContext _context;
    private readonly DbSet _dbSet;

    public EfCoreRepository(DbContext context)
    {
        _context = context;
        _dbSet = context.Set();
    }

    public async Task GetByIdAsync(int id)
    {
        return await _dbSet.FindAsync(id);
    }

    // 其他方法实现...
}

三、分层架构的进阶实践

1. 跨层通信规范

各层间应通过明确接口交互,避免直接引用。推荐使用DTO(Data Transfer Object)模式:

// DTO 示例
public class ProductDto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

// 实体映射(可使用AutoMapper)
public static class MappingExtensions
{
    public static ProductDto ToDto(this Product product)
    {
        return new ProductDto
        {
            Id = product.Id,
            Name = product.Name,
            Price = product.Price
        };
    }
}

2. 依赖注入配置

在.NET Core中,通过Program.cs集中配置服务依赖:

// Program.cs 依赖注入配置
var builder = WebApplication.CreateBuilder(args);

// 数据库上下文
builder.Services.AddDbContext(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));

// 仓储层
builder.Services.AddScoped();

// 业务服务层
builder.Services.AddScoped();

// API 控制器自动解析
builder.Services.AddControllers();

3. 异常处理机制

定义自定义异常类型,通过中间件统一处理:

// 自定义异常
public class BusinessException : Exception
{
    public BusinessException(string message) : base(message) { }
}

// 异常处理中间件
public class ExceptionHandlingMiddleware
{
    private readonly RequestDelegate _next;

    public ExceptionHandlingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (BusinessException ex)
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsJsonAsync(new { Error = ex.Message });
        }
        catch (Exception ex)
        {
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { Error = "Internal Server Error" });
        }
    }
}

四、常见架构变体

1. 六边形架构(Hexagonal Architecture)

强调"端口与适配器"模式,将核心业务逻辑置于中心,外部依赖通过适配器接入:

// 端口定义
public interface IOrderProcessor
{
    Task ProcessOrder(Order order);
}

// 适配器实现(邮件通知)
public class EmailOrderAdapter : IOrderProcessor
{
    public async Task ProcessOrder(Order order)
    {
        await SendEmailAsync(order.CustomerEmail, $"订单 {order.Id} 已创建");
    }

    private async Task SendEmailAsync(string to, string body)
    {
        // 邮件发送逻辑
    }
}

2. 垂直切片架构(Vertical Slice Architecture)

按功能模块而非技术层次组织代码,每个切片包含完整流程:

// 订单处理切片
namespace Features.Orders
{
    public class CreateOrder
    {
        public class Command : IRequest
        {
            public int CustomerId { get; set; }
            public List Items { get; set; }
        }

        public class Handler : IRequestHandler
        {
            private readonly IOrderRepository _repository;

            public Handler(IOrderRepository repository)
            {
                _repository = repository;
            }

            public async Task Handle(Command request, CancellationToken ct)
            {
                var order = new Order(request.CustomerId, request.Items);
                await _repository.AddAsync(order);
                return order.ToDto();
            }
        }
    }
}

五、性能优化策略

1. 缓存机制

使用MemoryCache或分布式缓存(Redis):

// 内存缓存示例
public class CachedProductService : IProductService
{
    private readonly IProductService _innerService;
    private readonly IMemoryCache _cache;

    public CachedProductService(IProductService innerService, IMemoryCache cache)
    {
        _innerService = innerService;
        _cache = cache;
    }

    public async Task GetProductAsync(int id)
    {
        return await _cache.GetOrCreateAsync($"product_{id}", async entry =>
        {
            entry.SlidingExpiration = TimeSpan.FromMinutes(5);
            return await _innerService.GetProductAsync(id);
        });
    }
}

2. 异步编程

所有I/O操作应使用async/await模式:

// 异步数据访问
public class AsyncProductRepository : IProductRepository
{
    private readonly DbContext _context;

    public AsyncProductRepository(DbContext context)
    {
        _context = context;
    }

    public async Task GetByIdAsync(int id)
    {
        return await _context.Set()
                             .FirstOrDefaultAsync(p => p.Id == id);
    }
}

六、测试策略

1. 单元测试

使用xUnit和Moq测试业务逻辑:

// 单元测试示例
public class OrderServiceTests
{
    [Fact]
    public async Task PlaceOrder_WhenInventoryAvailable_ShouldSucceed()
    {
        // 模拟依赖
        var mockRepo = new Mock();
        var mockInventory = new Mock();
        mockInventory.Setup(x => x.CheckStockAsync(It.IsAny>()))
                     .ReturnsAsync(new InventoryCheckResult { IsAvailable = true });

        var service = new OrderService(mockRepo.Object, mockInventory.Object);
        var result = await service.PlaceOrderAsync(new OrderRequest { Items = new List { ... } });

        Assert.True(result.IsSuccess);
    }
}

2. 集成测试

使用TestServer测试完整请求流程:

// 集成测试示例
public class ProductsApiTests : IClassFixture>
{
    private readonly HttpClient _client;

    public ProductsApiTests(WebApplicationFactory factory)
    {
        _client = factory.CreateClient();
    }

    [Fact]
    public async Task GetProduct_ReturnsOk()
    {
        var response = await _client.GetAsync("/api/products/1");
        response.EnsureSuccessStatusCode();
        var product = await response.Content.ReadFromJsonAsync();
        Assert.NotNull(product);
    }
}

七、现代.NET架构趋势

1. 微服务化

将单体应用拆分为独立服务,每个服务拥有自己的数据库和UI:

// 服务间通信(gRPC示例)
[ServiceContract]
public interface IInventoryService
{
    [OperationContract]
    Task CheckStockAsync(List items);
}

// 客户端调用
var channel = GrpcChannel.ForAddress("https://inventory-service");
var client = channel.CreateGrpcService();
var result = await client.CheckStockAsync(items);

2. 服务器less架构

使用Azure Functions或AWS Lambda处理无状态操作:

// Azure Function 示例
[FunctionName("ProcessOrder")]
public static async Task Run(
    [HttpTrigger(AuthorizationLevel.Function, "post")] OrderRequest request,
    [Inject] IOrderService orderService,
    ILogger log)
{
    try
    {
        var result = await orderService.PlaceOrderAsync(request);
        return new OkObjectResult(result);
    }
    catch (Exception ex)
    {
        log.LogError(ex, "订单处理失败");
        return new BadRequestObjectResult(ex.Message);
    }
}

关键词:.NET架构、三层架构、依赖注入DTO模式仓储模式、异常处理、异步编程、微服务、单元测试、领域驱动设计

简介:本文系统阐述了.NET环境下的逻辑分层架构设计,从经典三层架构到现代微服务架构,涵盖依赖管理、异常处理、性能优化等关键实践,结合代码示例说明各层实现细节,为构建高可维护性.NET应用提供完整指南。