Skip to content

Latest commit

 

History

History
152 lines (122 loc) · 6.23 KB

common-infrastructure.md

File metadata and controls

152 lines (122 loc) · 6.23 KB

Common Infrastructure

Infrastructure types that skills and templates reference. The default set (ADR-008) is the modular-slices building blocks. Their full, copyable code lives in skills/modular-slices/references/building-blocks.md; this page summarizes what each piece is for and holds the small types that do not belong to one skill.

Default Building Blocks

Type Purpose Code
IModule Describes a module; hosts add it with builder.AddModule<T>() building-blocks.md
IEndpoint One feature's endpoint; discovered by app.MapModules() (or app.MapEndpoints() in a single project) building-blocks.md
IHandler Marker that registers a feature handler as scoped; HandleAsync returns a TypedResults union building-blocks.md
RequestValidation One endpoint filter factory that runs FluentValidation for any parameter with a validator building-blocks.md
Problems + ErrorCodes ProblemDetails results with a stable code (not-found, <module>.<reason>) building-blocks.md
UnexpectedErrorHandler The one IExceptionHandler: concurrency conflicts to 409, everything else to 500 building-blocks.md
RequirePermission Declares the permission an endpoint needs building-blocks.md
ModuleDbContext Schema per module, concurrency, archive and tenant filters, outbox tables building-blocks.md
Outbox / inbox db.Publish(evt, clock), IEventConsumer<T>, the delivery worker skills/modular-slices/references/outbox.md

A handler with these pieces looks like this:

internal sealed class GetOrderHandler(OrdersDbContext db) : IHandler
{
    public async Task<Results<Ok<OrderResponse>, ProblemHttpResult>> HandleAsync(Guid id, CancellationToken ct)
    {
        var order = await db.Orders.AsNoTracking()
            .Where(o => o.Id == id)
            .Select(o => new OrderResponse(o.Id, o.ProductId, o.Quantity, o.Total, o.PlacedAt))
            .FirstOrDefaultAsync(ct);

        return order is null ? Problems.NotFound() : TypedResults.Ok(order);
    }
}

Pagination

Lists are always paged, with the page size capped so a client cannot ask for the whole table.

// PageRequest.cs
public sealed record PageRequest(int Page = 1, int PageSize = 20)
{
    public int Skip => (Page - 1) * PageSize;
}

internal sealed class PageRequestValidator : AbstractValidator<PageRequest>
{
    public PageRequestValidator()
    {
        RuleFor(p => p.Page).GreaterThanOrEqualTo(1);
        RuleFor(p => p.PageSize).InclusiveBetween(1, 50);
    }
}

// Page.cs
public sealed record Page<T>(IReadOnlyList<T> Items, int TotalCount, int PageNumber, int PageSize)
{
    public int TotalPages => (int)Math.Ceiling(TotalCount / (double)PageSize);
    public bool HasPrevious => PageNumber > 1;
    public bool HasNext => PageNumber < TotalPages;
}

public static class PagingExtensions
{
    public static async Task<Page<T>> ToPageAsync<T>(this IQueryable<T> query, PageRequest page, CancellationToken ct)
    {
        var total = await query.CountAsync(ct);
        var items = await query.Skip(page.Skip).Take(page.PageSize).ToListAsync(ct);
        return new Page<T>(items, total, page.Page, page.PageSize);
    }
}

// Endpoint: [AsParameters] binds page and pageSize from the query string; the validation filter checks them
private static Task<Ok<Page<OrderSummary>>> HandleAsync(
    [AsParameters] PageRequest page, ListOrdersHandler handler, CancellationToken ct) =>
    handler.HandleAsync(page, ct);

The query must have a stable OrderBy before paging, or rows can repeat or go missing between pages.

Quick Setup Checklist

Program.cs for an Api host:

// Services
builder.AddModule<CatalogModule>();
builder.AddModule<OrdersModule>();
builder.Services.AddProblemDetails(options => options.CustomizeProblemDetails = context =>
{
    context.ProblemDetails.Extensions.TryAdd("code", ErrorCodes.ForStatus(context.ProblemDetails.Status ?? 500));
    context.ProblemDetails.Extensions["traceId"] = Activity.Current?.Id ?? context.HttpContext.TraceIdentifier;
});
builder.Services.AddExceptionHandler<UnexpectedErrorHandler>();

// Middleware (order matters)
app.UseExceptionHandler();
app.UseStatusCodePages();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();

// Endpoints
app.MapModules();

AddModule<T>() registers each module's validators, so there is no separate AddValidatorsFromAssembly call. Required package: FluentValidation.DependencyInjectionExtensions (add with dotnet add package, no version flag).

Alternatives

These are not the default. Use them when a codebase already does, or for code that is not an HTTP handler.

Result for non-HTTP code

Domain services shared by several handlers, background jobs and class libraries can return a Result<T> with typed errors instead of HTTP results. The error-handling skill has the type and shows how a handler turns a failed result into a Problems.* response. Do not put a Result<T> between an endpoint and its handler: the TypedResults union already carries the outcome.

IEndpointGroup (one class per resource)

Older kit versions grouped all endpoints of a resource in one IEndpointGroup class. Existing codebases may keep it; do not mix it with IEndpoint in the same project.

public interface IEndpointGroup
{
    void Map(IEndpointRouteBuilder app);
}

public static class EndpointGroupExtensions
{
    public static WebApplication MapEndpoints(this WebApplication app)
    {
        var groups = typeof(Program).Assembly.GetTypes()
            .Where(t => t is { IsClass: true, IsAbstract: false } && typeof(IEndpointGroup).IsAssignableFrom(t));
        foreach (var type in groups)
            ((IEndpointGroup)Activator.CreateInstance(type)!).Map(app);
        return app;
    }
}

// Alternative only: one class maps every endpoint for a resource
public sealed class OrderEndpoints : IEndpointGroup
{
    public void Map(IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/api/orders").WithTags("Orders");
        group.MapGet("/", ListOrders);
        group.MapPost("/", CreateOrder);
    }
}

The default replaces it because each operation in its own IEndpoint keeps a feature in one folder and stops unrelated changes from touching the same file.