Theon.Monolith.Cli 1.0.0

dotnet tool install --global Theon.Monolith.Cli --version 1.0.0
                    
This package contains a .NET tool you can call from the shell/command line.
dotnet new tool-manifest
                    
if you are setting up this repo
dotnet tool install --local Theon.Monolith.Cli --version 1.0.0
                    
This package contains a .NET tool you can call from the shell/command line.
#tool dotnet:?package=Theon.Monolith.Cli&version=1.0.0
                    
nuke :add-package Theon.Monolith.Cli --version 1.0.0
                    

Monolith CLI

基于 Clean Architecture 的 .NET 8/9/10 Web API 项目脚手架工具,提供完整的企业级应用基础架构,内置 AI Agent 服务和 LLM 集成能力。

目录


项目概述

Theon.Monolith CLI 是一个 .NET CLI 工具,用于脚手架生成生产级 ASP.NET Core 8/9/10 Web API 项目。它生成遵循 Clean Architecture 的解决方案,预配置最佳实践、现代库和企业模式。

核心特性

特性 说明
多框架支持 .NET 8.0 (LTS) / 9.0 (STS) / 10.0 (Preview)
多数据库支持 SQL Server / MySQL / PostgreSQL / SQLite
Clean Architecture 四层分层架构,依赖反转
JWT 认证 Access Token + Refresh Token 机制
企业微信 SSO 内置企业微信 OAuth 集成
OAuth2 服务 完整的 OAuth2 授权服务器(支持 PKCE、Client Credentials)
邮件模块 SMTP + Razor 模板 + 后台队列
AI Agent 服务 LLM 集成 + 工具调用能力 + SSE 流式对话
文件服务 文件上传下载 + 存储抽象

CLI 工具架构

架构图

┌─────────────────────────────────────────────────────────────────────────────┐
│                           Theon.Monolith.Cli                                 │
│                         (CLI Application Layer)                              │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐              │
│  │   Program.cs    │  │   Commands/     │  │   Handlers/     │              │
│  │                 │  │                 │  │                 │              │
│  │  Entry Point    │  │  NewCommand     │  │  NewCommand     │              │
│  │  Command Root   │  │  VersionCommand │  │  Handler        │              │
│  └────────┬────────┘  └────────┬────────┘  └────────┬────────┘              │
│           │                    │                    │                        │
│           └────────────────────┼────────────────────┘                        │
│                                │                                             │
│                                ▼                                             │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                        Validators/                                    │    │
│  │  ┌───────────────────────┐  ┌───────────────────────┐                │    │
│  │  │ ProjectNameValidator  │  │   ValidationResult    │                │    │
│  │  │ · 路径穿越检查        │  │   · IsValid           │                │    │
│  │  │ · 保留名称检查        │  │   · Error             │                │    │
│  │  │ · C# 关键字检查       │  │                       │                │    │
│  │  └───────────────────────┘  └───────────────────────┘                │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                │                                             │
│                                ▼                                             │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                         Templates/                                    │    │
│  │  ┌───────────────────────┐  ┌───────────────────────┐                │    │
│  │  │   ProjectTemplate.cs  │  │  PackageVersions.json │                │    │
│  │  │ · Scriban 渲染引擎    │  │  · NuGet 版本管理     │                │    │
│  │  │ · 文件生成逻辑        │  │  · 框架差异化配置     │                │    │
│  │  │ · 路径变量替换        │  │                       │                │    │
│  │  └───────────────────────┘  └───────────────────────┘                │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                │                                             │
│                                ▼                                             │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                          Helpers/                                     │    │
│  │  ┌───────────────────────────────────────────────────────────────┐  │    │
│  │  │                      DotNetHelper.cs                           │  │    │
│  │  │  · 封装 dotnet CLI 调用                                        │  │    │
│  │  │  · 执行 restore / new sln / add 命令                          │  │    │
│  │  └───────────────────────────────────────────────────────────────┘  │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────────────────────┘

文件结构

src/Theon.Monolith.Cli/
├── Program.cs                    # 入口点,注册命令
├── Theon.Monolith.Cli.csproj    # 项目文件
│
├── Commands/                     # 命令定义
│   ├── NewCommand.cs            # new 命令定义
│   └── VersionCommand.cs        # version 命令
│
├── Handlers/                     # 命令处理器
│   ├── NewCommandHandler.cs     # new 命令执行逻辑
│   └── NewCommandOptions.cs     # 命令参数
│
├── Validators/                   # 验证器
│   ├── ProjectNameValidator.cs  # 项目名称验证
│   └── ValidationResult.cs      # 验证结果
│
├── Helpers/
│   └── DotNetHelper.cs          # dotnet CLI 封装
│
└── Templates/                    # Scriban 模板引擎
    ├── ProjectTemplate.cs       # 模板渲染
    ├── PackageVersions.json     # NuGet 版本配置
    └── project/                 # 模板文件目录

命令处理流程

用户输入: theon-monolith new MyApi --framework net9.0 --db postgresql
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│  1. Program.cs 解析命令行参数                                                │
│     └── rootCommand.Parse(args).InvokeAsync()                               │
└─────────────────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│  2. NewCommand.SetAction 执行                                               │
│     └── 解析参数,创建 NewCommandOptions                                     │
│     └── 调用 NewCommandHandler.ExecuteAsync(options)                        │
└─────────────────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│  3. NewCommandHandler 验证                                                  │
│     ├── ProjectNameValidator.Validate(name)                                 │
│     │   ├── 检查路径穿越 (../)                                              │
│     │   ├── 检查保留名称 (CON, PRN, AUX...)                                 │
│     │   └── 检查 C# 关键字 (class, namespace...)                            │
│     ├── 验证 framework (net8.0/net9.0/net10.0)                              │
│     └── 验证 dbType (sqlserver/mysql/postgresql/sqlite)                     │
└─────────────────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│  4. ProjectTemplate.GenerateAsync()                                         │
│     ├── 加载 PackageVersions.json 获取 NuGet 版本                           │
│     ├── 创建 Scriban TemplateContext                                        │
│     │   └── ProjectName, Framework, DbType, ConnectionString...            │
│     ├── 渲染所有 .scribn 模板文件                                           │
│     ├── 复制所有 .copy 静态文件                                             │
│     └── 执行 dotnet new sln && dotnet sln add                               │
└─────────────────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│  5. DotNetHelper.Run("restore")                                             │
│     └── 还原 NuGet 包                                                       │
│     └── 输出成功信息                                                        │
└─────────────────────────────────────────────────────────────────────────────┘

模板系统架构

模板引擎

使用 Scriban 模板引擎,扩展名为 .scribn

核心组件:

组件 文件 职责
模板渲染器 ProjectTemplate.cs 加载、渲染、生成文件
版本管理 PackageVersions.json 管理三个框架的 NuGet 版本
模板文件 Templates/project/ 所有 .scribn.copy 文件

模板变量

所有 .scribn 模板中可用的变量:

变量 示例值 说明
ProjectName MyApi 用户提供的项目名称
ProjectNameLower myapi 小写变体
Framework net9.0 目标框架
FrameworkMajor 9 主版本号
DbType postgresql 数据库类型
DbTypeSqlSugar PostgreSQL SqlSugar 数据库类型
DbTypeNuGet Npgsql 数据库驱动包名
ConnectionString Host=localhost;... 默认连接字符串
Packages Dictionary<string, string> NuGet 版本字典
Guid GUID 新生成的 GUID
Year 2026 当前年份

模板文件类型

扩展名 处理方式 用途
.scribn Scriban 渲染 需要变量替换的文件
.copy 直接复制 静态文件(如 .gitignore

PackageVersions.json 结构

{
  "net8.0": {
    "Microsoft.AspNetCore.Authentication.JwtBearer": "8.0.16",
    "SqlSugarCore": "5.1.4.170",
    "MailKit": "4.16.0",
    "RazorLight": "2.3.1",
    ...
  },
  "net9.0": { ... },
  "net10.0": { ... }
}

路径变量替换

模板目录中的 {{ProjectName}} 会被替换为实际项目名:

Templates/project/
├── src/
│   └── {{ProjectName}}.Api/          → MyApi.Api/
│   └── {{ProjectName}}.Application/  → MyApi.Application/
│   └── {{ProjectName}}.Domain/       → MyApi.Domain/
│   └── {{ProjectName}}.Infrastructure/ → MyApi.Infrastructure/

生成项目架构

📖 详细架构文档: docs/ARCHITECTURE.md - 包含完整的技术栈、设计模式、依赖注入架构、数据访问模式等详细说明。

生成的项目遵循 Clean Architecture 原则,采用四层分层架构:

┌─────────────────────────────────────────────────────────────────┐
│                         Api Layer                                │
│  Controllers · Middleware · Filters · DI Configuration          │
├─────────────────────────────────────────────────────────────────┤
│                      Application Layer                           │
│  Services · Validators · Mappings · Behaviors · Options         │
├─────────────────────────────────────────────────────────────────┤
│                     Infrastructure Layer                         │
│  Persistence · Cache · Events · RateLimiting · Scheduling       │
├─────────────────────────────────────────────────────────────────┤
│                         Domain Layer                             │
│  Entities · Value Objects · Events · Exceptions · Interfaces    │
└─────────────────────────────────────────────────────────────────┘

四层详解

Domain Layer(领域层)

职责: 定义业务实体、领域事件、业务规则和领域异常。不依赖任何外部框架。

核心组件:

组件 说明
BaseEntity 实体基类,包含 Id、CreatedAt、UpdatedAt、IsDeleted
User 用户聚合根
IIntegrationEvent 集成事件标记接口
DomainException 领域异常基类,包含 ErrorCode 和 Errors
Application Layer(应用层)

职责: 编排业务用例,协调领域对象,定义应用服务接口。

核心组件:

组件 说明
ITokenService JWT 令牌生成服务
IProductService 产品服务
IOAuthService OAuth2 授权服务
IEmailService 邮件发送服务
IAgentChatService Agent 流式对话服务
IAgentAbilityService Agent 能力注册和执行
Validators FluentValidation 验证器
MappingConfig Mapster 对象映射配置
Options 强类型配置选项
Infrastructure Layer(基础设施层)

职责: 实现技术细节,包括数据库访问、缓存、消息、调度等。

核心组件:

组件 说明
SqlSugarSetup SqlSugar ORM 配置
SqlSugarAuditInterceptor 审计拦截器
MemoryCacheService 内存缓存实现
InMemoryEventBus 内存事件总线
SmtpEmailService SMTP 邮件服务
RazorEmailTemplateService Razor 模板渲染
OutputFilterPipeline Agent 输出过滤管道
ToolExecutionProtector Agent 工具执行保护
Api Layer(表现层)

职责: 处理 HTTP 请求,管理依赖注入,配置中间件管道。

核心组件:

组件 说明
AuthController 认证控制器
ProductsController 产品 CRUD 控制器
AgentController Agent 流式对话控制器
OAuthController OAuth2 授权端点
FilesController 文件上传下载控制器
CorrelationIdMiddleware 请求追踪中间件
ApiExceptionFilter 全局异常处理过滤器
AutofacModule 依赖注入模块

请求处理流程

HTTP Request
     │
     ▼
┌─────────────────────────────────────────────────────────────────┐
│                        Middleware Pipeline                       │
│  1. Serilog Request Logging                                     │
│  2. CorrelationIdMiddleware (X-Correlation-Id)                  │
│  3. ExceptionHandler                                            │
│  4. Hsts / HttpsRedirection                                     │
│  5. Cors                                                        │
│  6. Authentication                                              │
│  7. Authorization                                               │
│  8. RateLimiting                                                │
│  9. MapControllerRoute                                          │
└─────────────────────────────────────────────────────────────────┘
     │
     ▼
┌─────────────────────────────────────────────────────────────────┐
│                         Controller                               │
│  1. 接收请求 DTO                                                 │
│  2. 调用 Application Services                                   │
│  3. 返回响应 DTO                                                 │
└─────────────────────────────────────────────────────────────────┘
     │
     ▼
┌─────────────────────────────────────────────────────────────────┐
│                      Application Service                         │
│  1. 验证业务规则                                                 │
│  2. 操作 Domain Entities                                        │
│  3. 持久化通过 IUnitOfWork                                      │
│  4. 发布领域事件                                                 │
└─────────────────────────────────────────────────────────────────┘

技术栈

类别 技术 版本
框架 .NET 8.0 / 9.0 / 10.0
ORM SqlSugar 5.1.4+
DI 容器 Autofac 8.1.0 / 9.1.0
验证 FluentValidation 11.11.0 / 12.1.1
映射 Mapster 7.4.0 / 10.0.7
日志 Serilog 8.0+
邮件 MailKit + RazorLight 4.16.0 / 2.3.1
认证 JWT Bearer 8.0+
缓存 Memory Cache 8.0+
任务调度 Coravel 4.2.1 / 6.0.2
测试 xUnit + FluentAssertions + Moq Latest

快速开始

安装 CLI 工具

# 打包为 NuGet 工具
dotnet pack src/Theon.Monolith.Cli -c Release -o ./nupkg

# 从本地包全局安装
dotnet tool install --global --add-source ./nupkg Theon.Monolith.Cli

创建新项目

# 创建新项目(默认 .NET 8)
theon-monolith new MyProject

# 创建 .NET 9 项目
theon-monolith new MyProject --framework net9.0

# 指定数据库类型
theon-monolith new MyProject --db postgresql

# 预览将生成的文件
theon-monolith new MyProject --dry-run

# 指定输出目录
theon-monolith new MyProject --output ./src

# 跳过 dotnet restore
theon-monolith new MyProject --skip-restore

CLI 命令

命令 说明
theon-monolith new <name> 创建新项目
theon-monolith new <name> -f net9.0 指定 .NET 版本
theon-monolith new <name> --db postgresql 指定数据库类型
theon-monolith new <name> --dry-run 预览将生成的文件
theon-monolith new <name> -o ./src 指定输出目录
theon-monolith new <name> --skip-restore 跳过 dotnet restore
theon-monolith version 显示版本信息
theon-monolith --help 显示帮助信息

CLI 选项

选项 说明 默认值
-f, --framework 目标框架 (net8.0/net9.0/net10.0) net8.0
--db 数据库类型 (sqlserver/mysql/postgresql/sqlite) sqlserver
-o, --output 输出目录 当前目录
--skip-restore 跳过 restore false
--dry-run 预览模式 false

配置说明

数据库配置

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=mydb;User Id=sa;Password=123456;"
  },
  "Database": {
    "Type": "SqlServer"
  }
}

支持的数据库类型:

类型 Database:Type 值
SQL Server SqlServer
MySQL MySql
PostgreSQL PostgreSQL
SQLite Sqlite

JWT 配置

{
  "Jwt": {
    "Secret": "your-256-bit-secret-key-replace-in-production-min-32-chars",
    "Issuer": "MyProject",
    "Audience": "MyProjectUsers",
    "AccessTokenExpirationMinutes": 15,
    "RefreshTokenExpirationDays": 7
  }
}

Agent 配置

{
  "Agent": {
    "ContextWindow": {
      "MaxTotalTokens": 128000,
      "ReservedForOutput": 4096,
      "TrimmingStrategy": "SlidingWindow"
    },
    "InputFiltering": {
      "Enabled": true,
      "MaxInputLength": 10000,
      "EnableInjectionDetection": true
    },
    "OutputFiltering": {
      "Enabled": true,
      "EnablePiiMasking": true,
      "EnableContentFilter": true
    },
    "ToolExecution": {
      "DefaultTimeoutSeconds": 30,
      "MaxCallsPerTurn": 10,
      "EnableCircuitBreaker": true,
      "CircuitBreakerFailureThreshold": 3
    }
  }
}

邮件配置

{
  "Email": {
    "Host": "smtp.example.com",
    "Port": 587,
    "Username": "",
    "Password": "",
    "From": "noreply@example.com",
    "FromName": "MyProject",
    "UseSsl": true,
    "MaxRetryAttempts": 3,
    "RetryDelaySeconds": 30
  }
}

速率限制配置

{
  "IpRateLimiting": {
    "EnableEndpointRateLimiting": true,
    "HttpStatusCode": 429,
    "GeneralRules": [
      { "Endpoint": "*", "Period": "1m", "Limit": 60 },
      { "Endpoint": "POST:/api/auth/login", "Period": "1m", "Limit": 10 },
      { "Endpoint": "POST:/api/auth/register", "Period": "1m", "Limit": 5 }
    ]
  }
}

开发指南

构建命令

# 构建 CLI 工具
dotnet build Theon.Monolith.sln

# 本地运行 CLI(从项目根目录)
dotnet run --project src/Theon.Monolith.Cli -- --help

# 运行测试
dotnet test

# 打包
dotnet pack src/Theon.Monolith.Cli -c Release -o ./nupkg

添加新功能模块

  1. 添加 NuGet 包

    • 更新 src/Theon.Monolith.Cli/Templates/PackageVersions.json
    • 同时更新 net8.0、net9.0 和 net10.0 三个配置
  2. 添加模板文件

    • src/Theon.Monolith.Cli/Templates/project/ 中添加 .scribn 文件
    • 使用路径占位符如 {{ProjectName}} 进行动态命名
  3. 注册服务

    • 更新 InfrastructureModule.cs.scribn 注册基础设施服务
    • 更新 ServiceCollectionExtensions.cs.scribn 注册配置选项

添加新数据库支持

  1. PackageVersions.json 添加驱动包
  2. ProjectTemplate.csCreateTemplateContext 方法添加映射
  3. NewCommandHandler.csValidDbTypes 数组添加类型

项目名称验证规则

ProjectNameValidator 执行以下检查:

  • 路径穿越检查(禁止 ../
  • Windows 保留名称检查(CON, PRN, AUX, NUL, COM1-9, LPT1-9
  • C# 关键字检查(class, namespace, interface 等)
  • 无效字符检查(仅允许字母、数字、下划线、连字符)

功能模块

认证授权

  • JWT Token 认证
  • Refresh Token 机制
  • Token 黑名单
  • 企业微信 SSO 集成
  • OAuth2 授权服务器(支持 PKCE、Client Credentials)

AI Agent 服务

  • LLM 集成(多模型支持:OpenAI、Anthropic、Azure)
  • SSE 流式对话
  • 工具调用能力(Tool Calling)
  • 会话管理
  • 能力注册与权限控制
  • 输入清洗(注入攻击检测)
  • 输出过滤(PII 脱敏、内容安全)
  • 上下文窗口管理
  • Token 计数(Tiktoken)

邮件服务

  • SMTP 发送(MailKit)
  • Razor 模板渲染(RazorLight)
  • 后台队列处理(Coravel)
  • 重试机制(指数退避)
  • 内置模板:密码重置、邮箱验证、欢迎邮件

文件服务

  • 文件上传下载
  • 存储抽象(本地存储、云存储)
  • 文件类型验证
  • 大小限制

异常处理

  • RFC 7807 ProblemDetails 标准
  • 结构化日志(Serilog)
  • 开发/生产环境区分
  • TraceId 追踪

版本兼容性

.NET 版本 状态
.NET 8.0 ✅ LTS,推荐生产使用
.NET 9.0 ✅ STS,最新特性
.NET 10.0 ✅ Preview,实验性
数据库 状态
SQL Server ✅ 默认
MySQL ✅ 支持
PostgreSQL ✅ 支持
SQLite ✅ 支持(开发/测试)

项目结构

theon-monolith-cli/
├── src/
│   └── Theon.Monolith.Cli/        # CLI 工具源码
│       ├── Commands/               # 命令定义
│       ├── Handlers/               # 命令处理器
│       ├── Validators/             # 输入验证
│       ├── Helpers/                # 辅助工具
│       └── Templates/              # 项目模板
│           └── project/            # 模板文件
│               ├── src/            # 四层项目模板
│               │   ├── {{ProjectName}}.Api/
│               │   ├── {{ProjectName}}.Application/
│               │   ├── {{ProjectName}}.Domain/
│               │   └── {{ProjectName}}.Infrastructure/
│               └── tests/          # 测试项目模板
├── tests/
│   └── Theon.Monolith.Cli.Tests/  # CLI 单元测试
├── docs/
│   └── ARCHITECTURE.md            # 架构文档
├── Theon.Monolith.sln             # 解决方案文件
├── CLAUDE.md                       # Claude Code 指引
└── README.md                       # 本文件

License

MIT License

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

This package has no dependencies.

Version Downloads Last Updated
1.0.0 107 5/10/2026