agentleFS
codewithmukeshcodewithmukesh/dotnet-agent-kit/skills/modular-slices/SKILL.md

modular-slices

Skill853 starsChanged yesterdayMITView on GitHub

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).

1 other project uses a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

1 rule. About 0 are common, 0 are distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Only the Worker host runs delivery (AddOutboxWorker()).

    line 174

≈ “Common” is an estimate: at least 1 in 5 of the 383,637 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Modular Slices

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 feature
  • references/hosts-and-projects.md: Api, Worker, Migrator and AppHost programs, project files, Directory.Build.props
  • references/outbox.md: per-module outbox and inbox, consumers, the worker, scheduled jobs
  • references/architecture-tests.md: boundary rules with proofs
  • references/testing.md: fixture, test auth, the four tests every feature gets

Core Principles

  1. A module is two projects: <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.
  2. A feature is a folder, and adding one touches nothing else. 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.
  3. Handlers return 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.
  4. Everything is 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.
  5. Each module owns its data and talks asynchronously through its outbox. One database, one schema per module, one 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.

Patterns

Solution layout

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/

The module class

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

A slice: endpoint + handler

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.

Request, validator, response

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.

Errors: ProblemDetails with stable codes

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).

Calling another module

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.");

Publishing and consuming events

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.

Hosts under Aspire

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.

Strict build

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.

Anti-patterns

Referencing another module's implementation

// 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.

Packages in a contracts project

<!-- 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.

A mediator or Result<T> between endpoint and handler

// 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.

Public handlers and entities

// 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.

Publishing outside the transaction

// 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);

Error codes as free text

// 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.");

One endpoint class per resource

// 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 */ }

Decision Guide

ScenarioRecommendation
New business application with several areasModular slices: one module per area, start with 2 to 4 modules
One area, a few endpoints, unlikely to growarchitecture-advisor (references/vertical-slice.md): same IEndpoint + IHandler + TypedResults, single project, no module split
Not sure where a module boundary goesSplit by data ownership: who creates and changes the rows. Merge modules that always change together
Module needs data owned by anotherCall an interface in the owner's Contracts; cache or copy via events if it is hot
Module must react to another's changeIntegration event in the publisher's Contracts + IEventConsumer<T> in the consumer
Logic shared by several handlers in one moduleinternal static helper or service under Features/Common/
Logic shared across modulesPut it behind the owning module's contract; only true building blocks go in Modularity
Rich invariants inside one moduleUse 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 failuresResult<T> is fine there (error-handling skill)
Recurring or scheduled workHangfire or a BackgroundService in the Worker host
Events must leave the processKeep the outbox; forward from the dispatcher to a broker (messaging skill)
Multi-tenant dataITenantOwned + the named tenant query filter in ModuleDbContext; test cross-tenant access returns 404
Built-in .NET 10 validation vs FluentValidationFluentValidation 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

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.