第二章:多层架构设计与项目搭建

博客v1.0系列教程(Csharp)博客 v1.0 系列教程 (C#)

2.1 项目结构搭建

使用 dotnet CLI 创建多层解决方案:

# 创建解决方案
dotnet new sln -n Blog

# 创建各层项目
dotnet new webapi -n Blog.Api
dotnet new classlib -n Blog.Common
dotnet new classlib -n Blog.Core
dotnet new classlib -n Blog.Domain
dotnet new classlib -n Blog.Services

# 添加到解决方案
dotnet sln add Blog.Api Blog.Common Blog.Core Blog.Domain Blog.Services

项目引用关系

Blog.Api → Blog.Services → Blog.Core → Blog.Domain
                                       → Blog.Common
Blog.Services → Blog.Core → Blog.Domain
                          → Blog.Common

2.2 依赖注入配置

Blog.Api/Program.cs 中配置依赖注入:

// 注册服务
builder.Services.AddScoped<IArticleService, ArticleService>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<ICommentService, CommentService>();

// 注册基础设施
builder.Services.AddSingleton<ITokenService, TokenService>();
builder.Services.AddSingleton<IRedisService, RedisService>();

// 注册仓储
builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>));

2.3 配置文件设计

采用拆分配置的方式,按模块分离:

// appsettings.json
{
  "Database": {
    "Provider": "PostgreSQL",
    "ConnectionString": "Host=localhost;Port=5432;DB=blog;..."
  },
  "JWT": {
    "Secret": "your-secret-key",
    "Issuer": "Blog",
    "Audience": "Blog",
    "ExpireMinutes": 1440
  },
  "Redis": {
    "ConnectionString": "localhost:6379"
  }
}

2.4 中间件管道

在 Program.cs 中配置中间件:

app.UseMiddleware<ExceptionMiddleware>();
app.UseAuthentication();
app.UseAuthorization();
app.MapEndpoints();

2.5 Minimal API 端点注册

使用扩展方法组织端点:

public static class ArticleEndpoints
{
    public static void MapArticleEndpoints(this WebApplication app)
    {
        var group = app.MapGroup("/api/article");
        group.MapGet("/", GetArticles);
        group.MapGet("/{id}", GetArticleById);
        group.MapPost("/", CreateArticle);
        group.MapPut("/", UpdateArticle);
        group.MapDelete("/{id}", DeleteArticle);
    }
}

下一章将深入数据模型与数据库设计。

csharpdotnet架构project-structure