Rules: events, behaviors and overrides

Three ways to add logic, from most to least common. All are found automatically.

1. Page events: CrudPageEvents<TModel>

One class per page with the moments you need; override only those (the rest cost nothing).

public class CityEvents : CrudPageEvents<CityModel>
{
    protected override Task OnValidatingAsync(Validating<CityModel> e, CancellationToken ct)
    {
        if (e.Model.Population < 0) e.AddError("population", "Population can't be negative.");   // → 400
        return Task.CompletedTask;
    }

    protected override Task OnDeletingAsync(Deleting<CityModel> e, CancellationToken ct)
    {
        if (e.Model.IsCapital) e.Cancel("Capital cities can't be deleted.");                     // → 409
        return Task.CompletedTask;
    }
}
Before (can add errors or cancel) After
OnListingAsync (change the query, add model filters) OnListedAsync
OnViewingAsync (cancel → 403) OnViewedAsync
OnValidatingAsync  
OnCreatingAsync (change the model) OnCreatedAsync
OnUpdatingAsync (e.Original holds the stored values) OnUpdatedAsync
OnDeletingAsync OnDeletedAsync
OnRestoringAsync, OnPurgingAsync (soft-delete pages) OnRestoredAsync, OnPurgedAsync

After-events run after the commit by default: a failure there is logged and the caller still gets success (o.ThrowOnAfterCommitFailure = true to fail instead). Override Phase => EventPhase.InTransaction to run inside the save’s transaction, where a failure rolls the change back.

2. Handlers for many pages: ICrudEventHandler<T>

public class AuditLog(ILogger<AuditLog> log) : ICrudEventHandler<ICreated>
{
    public Task HandleAsync(ICreated e, CancellationToken ct)
    {
        log.LogInformation("{Page} {Id} created", e.Page, e.Id);
        return Task.CompletedTask;
    }
}

Handle an interface (ICreated, IUpdated, IDeleted, IPageEvent, …) for every page, or one page’s event (Created<CityModel>). Your own events work too: publish them with ICrudEventPublisher. Domain events: an entity with a DomainEvents collection has them dispatched after the save (or in its transaction). Implement ICrudEventHandlerSettings for Order and Phase.

3. Behaviors: wrap whole operations

public class TimingBehavior<TModel>(ILogger<TimingBehavior<TModel>> log) : ICrudBehavior<TModel> where TModel : class
{
    public async Task<TModel> CreateAsync(TModel model, Func<TModel, CancellationToken, Task<TModel>> next, CancellationToken ct)
    {
        var started = Stopwatch.GetTimestamp();
        var result = await next(model, ct);
        log.LogInformation("Created in {Ms} ms", Stopwatch.GetElapsedTime(started).TotalMilliseconds);
        return result;
    }
}

A generic class covers every page; ICrudBehavior<CityModel> covers one. Wrap only what you need: list, get, create, update, delete, create-with-key, the deleted list, restore, purge. Lower Order wraps outermost.

Several saves as one: CrudUnitOfWork

await using var unit = unitOfWork.Begin();          // CrudUnitOfWork, scoped
var order = await orders.CreateAsync(newOrder, ct);
await lines.CreateAsync(new LineModel { OrderId = order.Id, ... }, ct);
await unit.CommitAsync(ct);                          // or leave without it: everything is rolled back

While a unit is active, every save joins one transaction (per database), in-transaction handlers run as usual, and after-commit handlers wait until CommitAsync. Without a commit they never run. A failing save throws as usual and the unit stays usable, so the caller decides whether to go on. The pro import uses it: a check is the import, rolled back.

Your own transaction. When your code opens an EF Core transaction (db.Database.BeginTransactionAsync()) and engine saves run inside it, with or without a unit, their after-commit handlers wait for your commit and never run if you roll back.

Retries (EnableRetryOnFailure). Single operations (create, update, delete, restore, purge) run through the context’s execution strategy: after a transient failure the whole operation runs again (load, validate, apply, save), with the failed attempt’s changes discarded. A unit of work or your own transaction isn’t retried by the engine: run it inside the strategy yourself:

var strategy = db.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async ct =>
{
    await using var unit = unitOfWork.Begin();
    ...                                   // engine saves
    await unit.CommitAsync(ct);
}, cancellationToken);

What behaviors wrap. ICrudBehavior<TModel> wraps list, get, create, update, delete, create-with-key, the deleted list, restore and purge. It doesn’t wrap lookups, unique checks (IsUniqueAsync), FindKeyAsync or IsVisibleAsync: put rules for those in an override of the service, or rely on the tenant filter and row rules, which cover every call.

Overriding one method

Every engine class is non-sealed and every public/protected member is virtual. Subclass and override one step; the rest keeps working. Subclasses are found automatically.

public class NationalityService(CrudServiceContext<NationalityModel, Nationality> context)
    : CrudService<NationalityModel, Nationality>(context)
{
    protected override Task MapToEntityAsync(NationalityModel model, Nationality entity, bool isNew, CancellationToken ct)
    {
        model.Name = string.Join(' ', model.Name.Split(' ', StringSplitOptions.RemoveEmptyEntries));   // tidy spaces
        return base.MapToEntityAsync(model, entity, isNew, ct);
    }
}

The same works for CrudController<TModel>, PageMapper<,>, CrudQueryBuilder<,>, PageReader<,> and every provider and option class. App-wide bases: o.UseServiceBase(typeof(AppCrudService<,>)), AddHttpApi(o => o.UseControllerBase(typeof(AppCrudController<>))).

Rich domain entities: ICrudDomainAdapter

When an entity guards its own state (private setters, a factory method, behavior methods), the engine can’t copy form fields onto it. Give the page an adapter and the engine calls the domain’s own methods instead:

public class CourseAdapter : ICrudDomainAdapter<CourseModel, Course>
{
    public Task<Course> CreateAsync(CourseModel m, CancellationToken ct) =>
        Task.FromResult(Course.Create(m.Name, m.DurationWeeks));          // the factory checks the rules

    public Task UpdateAsync(CourseModel m, Course course, CancellationToken ct)
    {
        course.Rename(m.Name);
        course.ChangeDuration(m.DurationWeeks);
        return Task.CompletedTask;
    }

    public Task DeletingAsync(Course course, CancellationToken ct)        // optional
    {
        course.Retire();                                                 // may throw, may raise a domain event
        return Task.CompletedTask;
    }
}

It’s found automatically (one per page) and needs only Abstractions, so it works in Strict mode. Validation, events, tenant stamping, audit and transactions stay the engine’s. Domain events the entity collects in a public DomainEvents list are dispatched as usual, also on delete. A domain exception becomes an HTTP status with o.MapException<TException>(status).

Strict or pragmatic

  • Strict: your Application layer references only Abstractions, so it uses events, handlers, behaviors and domain adapters.
  • Pragmatic: it also references Core, so it can subclass services and mappers.

Both are supported; the examples’ architecture tests show how to enforce either.