rea-analysis-optimization
MOmorluto/rea485k近 7 天新增 9,215 个 star
Default architecture for .NET business apps: modular monolith of vertical slices with Contracts projects, Features/<VerbPhrase>/ folders (IEndpoint + IHandler), IModule discovery, a DbContext per module. Use for "modular monolith", "IModule", "IHandler", "contracts project", "module boundaries", or adding a feature under src/Modules/. Do NOT use for small single-area APIs, Clean Architecture or DDD codebases (use architecture-advisor).
A modular monolith built from vertical slices. This is the kit's default for business applications (ADR-008). Each business area is a module with its own projects, schema and public contracts; each operation inside a module is a slice in its own folder. Full code to copy lives in references/:
references/building-blocks.md: IModule, IEndpoint, IHandler, discovery, validation filter, Problems, permissions, ModuleDbContext, a full featurereferences/hosts-and-projects.md: Api, Worker, Migrator and AppHost programs, project files, Directory.Build.propsreferences/outbox.md: per-module outbox and inbox, consumers, the worker, scheduled jobsreferences/architecture-tests.md: boundary rules with proofsreferences/testing.md: fixture, test auth, the four tests every feature gets<Module> and <Module>.Contracts. Other modules may reference only the contracts, which hold interfaces, the records they return, and integration events, with no package or framework references. The compiler then enforces the boundary, and EF Core or ASP.NET Core types cannot leak into what other modules see.Features/PlaceOrder/ holds PlaceOrderEndpoint, PlaceOrderHandler, PlaceOrderRequest, PlaceOrderRequestValidator and, if it is specific, the response. IEndpoint and IHandler are discovered, validators are registered by assembly, so neither the module class nor Program.cs changes.TypedResults unions, not a Result<T>. Results<Created<OrderResponse>, ProblemHttpResult> is checked by the compiler and documented in OpenAPI automatically. There is no mediator and no mapping layer: the endpoint injects its handler and returns what it returns.internal except the module class and request/response records. Hosts can see only how to add the module; other modules can see only its contracts. Architecture tests fail the build if anything else becomes public.DbContext per module used directly (no repositories). A change and the events it causes commit together; a worker delivers them to other modules' consumers, each of which handles an event once.src/
Modularity/ # shared building blocks (the only shared code with behaviour)
Modules/
Catalog/Catalog/ # implementation
Catalog/Catalog.Contracts/ # ICatalog, ProductInfo, ProductRetired
Orders/Orders/
OrdersModule.cs
OrdersPermissions.cs
Domain/Order.cs
Features/
PlaceOrder/ # PlaceOrderEndpoint, Handler, Request, RequestValidator
GetOrder/
CancelOrder/
Common/OrderResponse.cs # shared by several features of this module only
Events/MarkOrderPaid.cs # IEventConsumer<PaymentReceived>
Persistence/OrdersDbContext.cs
Services/OrdersService.cs # implements IOrders from Orders.Contracts
Orders/Orders.Contracts/
Api/ Worker/ Migrator/ AppHost/ ServiceDefaults/
tests/
Architecture.Tests/ Testing/ Orders.Tests/Features/PlaceOrder/
public sealed class OrdersModule : IModule
{
public string Name => "Orders";
public string RouteSegment => "orders";
public void AddServices(IServiceCollection services, IConfiguration configuration)
{
services.AddModuleDbContext<OrdersDbContext>();
services.AddScoped<IOrders, OrdersService>(); // for other modules
services.AddEventConsumer<PaymentReceived, MarkOrderPaid, OrdersDbContext>(); // from Billing
}
}
// Api/Program.cs: one line per module, then one call to map them all
builder.AddModule<CatalogModule>();
builder.AddModule<OrdersModule>();
app.MapModules(); // /api/v1/{segment}, tagged per module, validation filter on every endpoint
internal sealed class CancelOrderEndpoint : IEndpoint
{
public void Map(IEndpointRouteBuilder endpoints) =>
endpoints.MapPost("/{id:guid}/cancel", HandleAsync)
.RequirePermission(OrdersPermissions.Manage)
.WithSummary("Cancels an order that has not shipped");
private static Task<Results<Ok<OrderResponse>, ProblemHttpResult>> HandleAsync(
Guid id, CancelOrderRequest request, CancelOrderHandler handler, CancellationToken ct) =>
handler.HandleAsync(id, request, ct);
}
internal sealed class CancelOrderHandler(OrdersDbContext db, TimeProvider clock) : IHandler
{
public async Task<Results<Ok<OrderResponse>, ProblemHttpResult>> HandleAsync(
Guid id, CancelOrderRequest request, CancellationToken ct)
{
if (await db.Orders.FirstOrDefaultAsync(o => o.Id == id, ct) is not { } order)
return Problems.NotFound();
if (order.Status is OrderStatus.Shipped or OrderStatus.Cancelled)
return Problems.Conflict("orders.cannot-cancel", $"The order is already {order.Status.ToString().ToLowerInvariant()}.");
order.Cancel(request.Reason, clock.GetUtcNow());
db.Publish(new OrderCancelled(order.Id, request.Reason), clock);
await db.SaveChangesAsync(ct);
return TypedResults.Ok(OrderResponse.From(order));
}
}
The endpoint is a thin adapter: route, permission, OpenAPI text, and a call. All logic sits in the handler, which tests reach through HTTP.
public sealed record CancelOrderRequest(string Reason); // public: OpenAPI reads its XML docs
internal sealed class CancelOrderRequestValidator : AbstractValidator<CancelOrderRequest>
{
public CancelOrderRequestValidator() => RuleFor(r => r.Reason).NotEmpty().MaximumLength(500);
}
One endpoint filter, added once by MapModules, runs the validator for any parameter that has one and returns a 400 ValidationProblem with code: validation-failed. Handlers never validate shape again; they check business rules only.
return Problems.NotFound(); // 404 not-found
return Problems.Conflict("orders.cannot-cancel", "The order already shipped."); // 409
return Problems.RuleBroken("orders.product-not-found", "..."); // 422
Clients switch on code, never on detail text. Business codes are <module>.<reason> in kebab case and the helper rejects any other shape. A record that belongs to another tenant is a 404, so callers cannot probe for IDs. Unexpected exceptions reach one IExceptionHandler that returns a 500 ProblemDetails (and maps DbUpdateConcurrencyException to 409 stale-version).
Synchronous reads go through the other module's contract interface; writes to another module happen through events.
// Catalog.Contracts
public interface ICatalog
{
Task<ProductInfo?> FindProductAsync(Guid productId, CancellationToken ct);
}
public sealed record ProductInfo(Guid Id, string Name, decimal Price);
// Orders handler
if (await catalog.FindProductAsync(request.ProductId, ct) is not { } product)
return Problems.RuleBroken("orders.product-not-found", "The product does not exist.");
db.Orders.Add(order);
db.Publish(new OrderPlaced(order.Id, order.Total), clock); // outbox row, same transaction
await db.SaveChangesAsync(ct);
internal sealed class InvoiceOrders(BillingDbContext db, TimeProvider clock) : IEventConsumer<OrderPlaced>
{
public async Task ConsumeAsync(OrderPlaced message, CancellationToken ct)
{
db.Invoices.Add(Invoice.For(message.OrderId, message.Total, clock.GetUtcNow()));
await db.SaveChangesAsync(ct); // committed with the inbox row by the dispatcher
}
}
Only the Worker host runs delivery (AddOutboxWorker()); the Api and Worker both add the same modules. See references/outbox.md.
Api (HTTP), Worker (outbox delivery and scheduled jobs) and Migrator (applies every module's migrations, then exits) share the modules. The AppHost starts Postgres, runs the Migrator, and starts the Api and Worker with WaitForCompletion(migrator). Migrations never run at API start-up, because several replicas would race.
Directory.Build.props sets TreatWarningsAsErrors, AnalysisLevel latest, Nullable enable, EnforceCodeStyleInBuild, and lock files with locked restore in CI. Start strict: loosening later is easy, tightening a large codebase is not.
// BAD: Orders.csproj references Catalog.csproj and queries its DbContext
var product = await catalogDb.Products.FindAsync([request.ProductId], ct);
// GOOD: reference Catalog.Contracts and call the published interface
var product = await catalog.FindProductAsync(request.ProductId, ct);
Why: once one module reads another's tables, neither schema can change without breaking the other, and the module can never be extracted.
<!-- BAD: Orders.Contracts.csproj -->
<PackageReference Include="Microsoft.EntityFrameworkCore" />
<!-- GOOD: no references at all -->
<Project Sdk="Microsoft.NET.Sdk" />
Why: every module that references the contracts inherits the package, and entity types start appearing in contracts.
// BAD: indirection plus a mapping layer
group.MapPost("/", async (PlaceOrder.Command cmd, ISender sender) =>
(await sender.Send(cmd)).ToHttpResult());
// GOOD: inject the handler; its return type is the HTTP contract
private static Task<Results<Created<OrderResponse>, ProblemHttpResult>> HandleAsync(
PlaceOrderRequest request, PlaceOrderHandler handler, CancellationToken ct) =>
handler.HandleAsync(request, ct);
Why: the union type is checked by the compiler and read by OpenAPI; a Result<T> hides the status codes until runtime.
// BAD
public class PlaceOrderHandler { }
public class Order { }
// GOOD
internal sealed class PlaceOrderHandler(OrdersDbContext db) : IHandler { }
internal sealed class Order { }
Why: anything public in a module becomes something a host or test helper will start depending on.
// BAD: the order can save while the event is lost, or the event goes out for an order that rolled back
await db.SaveChangesAsync(ct);
await bus.PublishAsync(new OrderPlaced(order.Id, order.Total), ct);
// GOOD
db.Publish(new OrderPlaced(order.Id, order.Total), clock);
await db.SaveChangesAsync(ct);
// BAD: clients end up matching on English sentences
return TypedResults.Problem("Order already cancelled", statusCode: 409);
// GOOD
return Problems.Conflict("orders.already-cancelled", "The order is already cancelled.");
// BAD: every change to any order operation edits this file
public sealed class OrderEndpoints : IEndpointGroup { /* 12 MapX calls */ }
// GOOD: one IEndpoint per feature folder
internal sealed class PlaceOrderEndpoint : IEndpoint { /* one MapPost */ }
| Scenario | Recommendation |
|---|---|
| New business application with several areas | Modular slices: one module per area, start with 2 to 4 modules |
| One area, a few endpoints, unlikely to grow | architecture-advisor (references/vertical-slice.md): same IEndpoint + IHandler + TypedResults, single project, no module split |
| Not sure where a module boundary goes | Split by data ownership: who creates and changes the rows. Merge modules that always change together |
| Module needs data owned by another | Call an interface in the owner's Contracts; cache or copy via events if it is hot |
| Module must react to another's change | Integration event in the publisher's Contracts + IEventConsumer<T> in the consumer |
| Logic shared by several handlers in one module | internal static helper or service under Features/Common/ |
| Logic shared across modules | Put it behind the owning module's contract; only true building blocks go in Modularity |
| Rich invariants inside one module | Use DDD aggregates inside that module (architecture-advisor, references/ddd.md); the module structure stays the same |
| Code that is not an HTTP handler needs typed failures | Result<T> is fine there (error-handling skill) |
| Recurring or scheduled work | Hangfire or a BackgroundService in the Worker host |
| Events must leave the process | Keep the outbox; forward from the dispatcher to a broker (messaging skill) |
| Multi-tenant data | ITenantOwned + the named tenant query filter in ModuleDbContext; test cross-tenant access returns 404 |
| Built-in .NET 10 validation vs FluentValidation | FluentValidation through the one filter for business apps; built-in AddValidation() is fine for small APIs with DataAnnotations |
Existing codebase using IEndpointGroup or Result<T> | Keep its conventions; do not mix styles within a module |
MOmorluto/rea485k近 7 天新增 9,215 个 star
MAmattpocock/skills336k近 7 天新增 5,004 个 star
MAmattpocock/skills336k近 7 天新增 5,004 个 star
MAmattpocock/skills336k近 7 天新增 5,004 个 star
MAmattpocock/skills336k近 7 天新增 5,004 个 star