跳到主要内容

IGeekFan.FreeKit.Modularity

ASP.NET Core 模块化单体启动协议,按业务边界拆分模块,各自维护服务和 API。

功能概览

功能说明
模块注册IModuleStartup 启动协议
API 前缀模块独立的 Area 路由
服务注册按模块注册服务到 DI 容器
中间件按模块注册中间件管道

安装

dotnet add package IGeekFan.FreeKit.Modularity

快速开始

场景:电商系统

订单、商品、用户各自独立模块。

1. 创建模块启动类

// OrderModule/Startup.cs
using IGeekFan.FreeKit.Modularity;

public class OrderStartup : IModuleStartup
{
public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
services.AddScoped<IOrderService, OrderService>();
}

public void Configure(WebApplication app, IWebHostEnvironment env)
{
// 模块初始化
}
}

2. 创建模块控制器

// OrderModule/Controllers/OrderController.cs
[ApiController]
[Route("api/[module]/[controller]")]
public class OrderController : ControllerBase
{
private readonly IOrderService _orderService;

public OrderController(IOrderService orderService) => _orderService = orderService;

[HttpGet("{id}")]
public async Task<IActionResult> GetById(Guid id)
{
var order = await _orderService.GetByIdAsync(id);
return Ok(order);
}

[HttpPost]
public async Task<IActionResult> Create([FromBody] CreateOrderRequest request)
{
var order = await _orderService.CreateAsync(request);
return Ok(order);
}
}

3. 宿主注册模块

// Host/Program.cs
using IGeekFan.FreeKit.Modularity;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddModule<OrderStartup>("order", builder.Configuration);
builder.Services.AddModule<ProductStartup>("product", builder.Configuration);

var app = builder.Build();

app.ConfigureModules(); // 执行模块 Configure

app.MapControllers();
app.Run();

4. 最终路由

模块路由
orderGET /api/order/order/{id}
productGET /api/product/product

核心 API

方法说明
AddModule<TStartup>(prefix, config)注册模块
ConfigureModules()执行所有模块 Configure
AddModuleRouting()单独注册路由约定

设计限制

  • 模块启动类需要无参构造函数
  • [module] 只影响使用该令牌的控制器
  • 一个控制器程序集只归属一个模块
  • 模块必须显式注册,不会自动扫描

相关文档