使用分层架构构建.NET Core应用程序:产品和订单管理

发布:2024-09-12 16:29 阅读:10 点赞:0

分层架构(Layered Architecture),也称为N-Tier架构,是一种传统的软件设计模式,通过将应用程序组织成逻辑层,每层具有特定的责任。这种方法改进了关注点的分离,使得应用程序更易于管理、测试和扩展。在此架构中,每一层通常仅与其直接上下层进行交互。

在本文中,我们将探讨如何使用.NET Core中的分层架构构建产品和订单服务。我们将分解每一层,解释其目的,并提供代码示例来演示各层之间的交互。

一. 什么是分层(N-Tier)架构?

分层架构将应用程序划分为多个层次,每一层具有特定的角色和责任。一个典型的N-Tier架构包括以下几个层次:

1. 表现层(Presentation Layer)

管理用户交互,通常通过Web界面或API实现。

2. 应用层(Application Layer)

协调应用程序的工作流,处理业务逻辑和事务。

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

封装核心业务规则和逻辑。

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

处理数据库操作和数据持久化。

5. 数据库层(Database Layer)

实际存储数据的数据库。

这种分层方法帮助确保应用程序的每个部分专注于单一的功能,提高了可维护性和可测试性。

二. 设置项目

让我们使用分层架构构建一个产品和订单服务。我们将创建一个.NET Core解决方案,其中包含四个项目来表示每一层。

1. 表现层(Presentation Layer)

表现层负责处理用户交互。在我们的案例中,这是一个Web API,提供管理产品和订单的端点。

API 控制器

using Microsoft.AspNetCore.Mvc;
using ProductOrder.Application.Interfaces;
using ProductOrder.Application.DTOs;

namespace ProductOrder.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        private readonly IProductService _productService;

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

        // 获取指定ID的产品
        [HttpGet("{id}")]
        public async Task GetProduct(Guid id)
        {
            var product = await _productService.GetProductByIdAsync(id);
            if (product == nullreturn NotFound();
            return Ok(product);
        }

        // 创建新产品
        [HttpPost]
        public async Task CreateProduct([FromBody] ProductDto productDto)
        {
            var product = await _productService.AddProductAsync(productDto);
            return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
        }

        // 其他操作...
    }

    [Route("api/[controller]")]
    [ApiController]
    public class OrdersController : ControllerBase
    {
        private readonly IOrderService _orderService;

        public OrdersController(IOrderService orderService)
        {
            _orderService = orderService;
        }

        // 创建新订单
        [HttpPost]
        public async Task CreateOrder(Guid productId, int quantity)
        {
            var order = await _orderService.CreateOrderAsync(productId, quantity);
            return CreatedAtAction(nameof(GetOrder), new { id = order.Id }, order);
        }

        // 获取指定ID的订单
        [HttpGet("{id}")]
        public async Task GetOrder(Guid id)
        {
            var order = await _orderService.GetOrderByIdAsync(id);
            if (order == nullreturn NotFound();
            return Ok(order);
        }

        // 其他操作...
    }
}

2. 应用层(Application Layer)

应用层管理应用程序的工作流,处理业务逻辑和数据访问的协调。

应用服务

using ProductOrder.Application.Interfaces;
using ProductOrder.Application.DTOs;
using ProductOrder.BLL.Interfaces;

namespace ProductOrder.Application.Services
{
    public class ProductService : IProductService
    {
        private readonly IProductManager _productManager;

        public ProductService(IProductManager productManager)
        {
            _productManager = productManager;
        }

        // 根据ID获取产品
        public async Task GetProductByIdAsync(Guid id)
        {
            var product = await _productManager.GetByIdAsync(id);
            return new ProductDto
            {
                Id = product.Id,
                Name = product.Name,
                Price = product.Price
            };
        }

        // 添加新产品
        public async Task AddProductAsync(ProductDto productDto)
        {
            var product = new Product
            {
                Name = productDto.Name,
                Price = productDto.Price
            };

            await _productManager.AddAsync(product);

            return new ProductDto
            {
                Id = product.Id,
                Name = product.Name,
                Price = product.Price
            };
        }

        // 其他方法...
    }

    public class OrderService : IOrderService
    {
        private readonly IOrderManager _orderManager;
        private readonly IProductManager _productManager;

        public OrderService(IOrderManager orderManager, IProductManager productManager)
        {
            _orderManager = orderManager;
            _productManager = productManager;
        }

        // 创建订单
        public async Task CreateOrderAsync(Guid productId, int quantity)
        {
            var product = await _productManager.GetByIdAsync(productId);
            if (product == nullthrow new Exception("产品未找到");

            var order = new Order
            {
                ProductId = productId,
                Quantity = quantity,
                OrderDate = DateTime.UtcNow,
                Product = product
            };

            await _orderManager.AddAsync(order);

            return new OrderDto
            {
                Id = order.Id,
                ProductId = order.ProductId,
                Quantity = order.Quantity,
                Total = order.Total,
                OrderDate = order.OrderDate
            };
        }

        // 其他方法...
    }
}

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

业务逻辑层包含核心业务规则和逻辑。它专注于问题域,实施业务规则,而不关心数据如何存储或呈现。

业务管理器

using ProductOrder.BLL.Interfaces;
using ProductOrder.DAL.Interfaces;
using ProductOrder.Domain.Entities;

namespace ProductOrder.BLL.Managers
{
    public class ProductManager : IProductManager
    {
        private readonly IProductRepository _productRepository;

        public ProductManager(IProductRepository productRepository)
        {
            _productRepository = productRepository;
        }

        // 根据ID获取产品
        public async Task GetByIdAsync(Guid id)
        {
            return await _productRepository.GetByIdAsync(id);
        }

        // 添加产品
        public async Task AddAsync(Product product)
        {
            await _productRepository.AddAsync(product);
        }

        // 其他方法...
    }

    public class OrderManager : IOrderManager
    {
        private readonly IOrderRepository _orderRepository;

        public OrderManager(IOrderRepository orderRepository)
        {
            _orderRepository = orderRepository;
        }

        // 根据ID获取订单
        public async Task GetByIdAsync(Guid id)
        {
            return await _orderRepository.GetByIdAsync(id);
        }

        // 添加订单
        public async Task AddAsync(Order order)
        {
            await _orderRepository.AddAsync(order);
        }

        // 其他方法...
    }
}

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

数据访问层负责与数据库交互。它包含封装检索和存储数据逻辑的仓储类。

仓储

using Microsoft.EntityFrameworkCore;
using ProductOrder.Domain.Entities;
using ProductOrder.DAL.Interfaces;

namespace ProductOrder.DAL.Repositories
{
    public class ProductRepository : IProductRepository
    {
        private readonly ApplicationDbContext _context;

        public ProductRepository(ApplicationDbContext context)
        {
            _context = context;
        }

        // 根据ID获取产品
        public async Task GetByIdAsync(Guid id)
        {
            return await _context.Products.FindAsync(id);
        }

        // 获取所有产品
        public async Task> GetAllAsync()
        {
            return await _context.Products.ToListAsync();
        }

        // 添加产品
        public async Task AddAsync(Product product)
        {
            await _context.Products.AddAsync(product);
            await _context.SaveChangesAsync();
        }

        // 更新产品
        public async Task UpdateAsync(Product product)
        {
            _context.Products.Update(product);
            await _context.SaveChangesAsync();
        }

        // 删除产品
        public async Task DeleteAsync(Guid id)
        {
            var product = await GetByIdAsync(id);
            if (product != null)
            {
                _context.Products.Remove(product);
                await _context.SaveChangesAsync();
            }
        }
    }

    public class OrderRepository : IOrderRepository
    {
        private readonly ApplicationDbContext _context;

        public OrderRepository(ApplicationDbContext context)
        {
            _context = context;
        }

        // 根据ID获取订单
        public async Task GetByIdAsync(Guid id)
        {
            return await _context.Orders.Include(o => o.Product).FirstOrDefaultAsync(o => o.Id ==

 id);
        }

        // 获取所有订单
        public async Task> GetAllAsync()
        {
            return await _context.Orders.Include(o => o.Product).ToListAsync();
        }

        // 添加订单
        public async Task AddAsync(Order order)
        {
            await _context.Orders.AddAsync(order);
            await _context.SaveChangesAsync();
        }

        // 更新订单
        public async Task UpdateAsync(Order order)
        {
            _context.Orders.Update(order);
            await _context.SaveChangesAsync();
        }

        // 删除订单
        public async Task DeleteAsync(Guid id)
        {
            var order = await GetByIdAsync(id);
            if (order != null)
            {
                _context.Orders.Remove(order);
                await _context.SaveChangesAsync();
            }
        }
    }
}

5. 依赖注入和启动配置

最后,我们在Startup.cs文件中配置依赖注入,并设置中间件管道。

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // 数据库上下文
        services.AddDbContext(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        // 仓储
        services.AddScoped();
        services.AddScoped();

        // 管理器(业务逻辑层)
        services.AddScoped();
        services.AddScoped();

        // 服务(应用层)
        services.AddScoped();
        services.AddScoped();

        // 控制器
        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

三. 结论

分层(N-Tier)架构通过将应用程序划分为逻辑层,每一层具有特定的责任,提供了明确的关注点分离。这种架构适用于构建易于维护、测试和扩展的应用程序。

在这个示例中,我们使用.NET Core构建了一个产品和订单服务,采用了分层架构。每一层(表现层、应用层、业务逻辑层和数据访问层)的实现确保了与上下层的直接交互,从而保持了代码库的整洁和组织性。

分层架构非常适合中到大型规模的应用程序,可以确保代码的模块化和可维护性。