共享功能
共享功能定义了所有模块共用的基础设施和约定。
基础设施积木
src/BuildingBlocks/ 包含所有模块共享的基础设施:
| 项目 | 说明 |
|---|---|
| IGeekFan.FreeKit.Infrastructure | Controller 基类、DDD 约定、中间件、Serilog |
| IGeekFan.FreeKit.Web | Web 扩展、静态文件、压缩 |
| IGeekFan.FreeKit.Auth.Client | OAuth2 SSO 客户端 |
| IGeekFan.FreeKit.CLI | 命令行工具 |
Controller 基类
所有控制器继承 FreeKitController:
[Authorize]
[ApiController]
[Route("api/[controller]")]
public abstract class FreeKitController : KitApiControllerBase
{
}
基类提供的功能
| 功能 | 说明 |
|---|---|
| 用户信息 | CurrentUser 访问当前用户 |
| 异常处理 | 统一的异常处理 |
| 日志记录 | 内置日志记录 |
| 模型验证 | 自动验证请求模型 |
使用示例
[ApiController]
[Route("api/[module]/[controller]")]
public class ArticleController : FreeKitController
{
private readonly IArticleService _articleService;
public ArticleController(IArticleService articleService)
{
_articleService = articleService;
}
[HttpGet]
public async Task<List<ArticleDto>> GetList()
{
// CurrentUser 可用
var userId = CurrentUser.Id;
return await _articleService.GetListAsync(userId);
}
}
模块启动类
每个模块实现 IModuleStartup:
public class IdentityModuleStartup : IModuleStartup
{
public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
// 注册服务
services.AddScoped<IUserService, UserService>();
services.AddScoped<IRoleService, RoleService>();
}
public void Configure(WebApplication app, IWebHostEnvironment env)
{
// 中间件配置
app.UseMiddleware<IdentityMiddleware>();
}
}
依赖注入
使用 Autofac 自动扫描:
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureContainer<ContainerBuilder>((_, cb) =>
{
cb.RegisterModule(new FreeKitModule([typeof(Program).Assembly]));
cb.RegisterModule(new UnitOfWorkModule([typeof(Program).Assembly]));
});
服务标记接口
| 接口 | 生命周期 | 适用场景 |
|---|---|---|
IScopedDependency | 每次请求 | 数据库操作、业务逻辑 |
ITransientDependency | 瞬时 | 无状态工具类 |
ISingletonDependency | 单例 | 缓存、配置、日志 |
使用示例
// 每次请求新实例
public class ArticleService : IScopedDependency
{
private readonly IFreeSql _fsql;
public ArticleService(IFreeSql fsql)
{
_fsql = fsql;
}
}
// 单例
public class CacheService : ISingletonDependency
{
private readonly IMemoryCache _cache;
public CacheService(IMemoryCache cache)
{
_cache = cache;
}
}
// 瞬时
public class EmailSender : ITransientDependency
{
private readonly IEmailSender _emailSender;
public EmailSender(IEmailSender emailSender)
{
_emailSender = emailSender;
}
}
中间件管道
var app = builder.Build();
// 中间件顺序(重要)
app.UseAuthentication();
app.UseCurrentUserAccessor(); // FreeKit 中间件
app.UseAuthorization();
app.MapControllers();
app.Run();
中间件说明
| 中间件 | 说明 |
|---|---|
UseAuthentication | 认证 |
UseCurrentUserAccessor | 设置 CurrentUser |
UseAuthorization | 授权 |
统一异常处理
// 业务异常
throw new BusinessException("Article not found");
// 404 异常
throw new NotFoundException("Article", id);
// 403 异常
throw new ForbiddenException("No permission");