1 后端代码规范文档
西街长安 edited this page 2026-01-30 21:34:53 +08:00
This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

项目规范文档

1. 命名规范

  • 全局命名

    • 采用 小驼峰命名法camelCase例如aBbCc
    • 特殊情况除外,例如 .NET 编译器要求方法名使用大驼峰PascalCase
  • 各层命名规范

    • Controllers:自定义命名 + Controller
    • Services:自定义命名 + Service
    • Dtos:自定义命名 + Dto

2. 文件/文件夹规范

文件夹 功能描述 注意事项
Controllers 存放控制器和 Actions用于处理请求和响应 禁止直接操作数据库。如需数据库操作,应先在 Services 层编写业务逻辑再调用
Services 存放业务逻辑代码,包括数据库交互 应在 Service 层处理所有业务逻辑,保证 Controller 层纯粹用于请求处理
Dtos 存放不同层之间的数据传输模型DTO 用于数据类型转换,例如返回用户信息时需剔除密码等敏感信息。禁止直接返回数据库模型类
Models 存放数据库模型类Entity 一般情况下请勿随意修改
appsettings.json 存放配置文件如数据库连接字符串、Redis 配置等 禁止在业务代码中硬编码配置信息,统一放在此文件中

3. Service 编写与使用规范

3.1 编写 Service

  1. Interface/Services 文件夹下创建接口,定义业务方法框架。
  2. 提交接口代码至 Gitea合并并通过审核。
  3. Services 文件夹下新建类,实现上述接口。

3.2 注册 Service

  1. Configs/ServiceCollectionExtensions.cs 文件的 AddAllService 方法中添加:
services.AddTransient<接口类型, 实现类>();
  1. 根据业务逻辑选择生命周期:

    • AddTransient:瞬时
    • AddScoped:请求范围
    • AddSingleton:单例

3.3 在 Controller 中使用 Service

  1. 在 Controller 内定义属性:
private readonly IDemo _demo;
  1. 在构造函数中通过依赖注入接收接口实例:
public WeatherForecastController(IDemo demo)
{
    _demo = demo;
}
  1. 在 Controller 方法中使用 _demo 调用业务逻辑方法。

4. 模型类字段使用规范

4.1 类中状态相关字段例如Status返回值为sbyte。若类中有同名字段+后缀Enum则优先使用后者,StatusEnum。

5.数据库相关

5.1 若数据库表结构更新,请在软件包控制台执行如下命令:

Scaffold-DbContext "Name=ConnectionStrings:DefaultConnection" Pomelo.EntityFrameworkCore.MySql -OutputDir Models -Context ImContext -Force -NoOnConfiguring