Skip to content

Events ​

Complete Example: Dispatch and Record ​

This file defines its event and caller; no undeclared order model or mailer is needed:

csharp
// app/Commands/EventDemo.cs
using DotBlaze;

namespace Blog.Commands;

public record DocumentPreviewed(long DocumentId) : IEvent;

public class EventDemo : Command
{
    public override string Signature => "demo:event";
    public override async Task<int> Handle()
    {
        var events = Event.Fake();
        await Event.Dispatch(new DocumentPreviewed(42));
        events.AssertDispatched<DocumentPreviewed>(value => value.DocumentId == 42);
        Line("DocumentPreviewed(42) dispatched.");
        return 0;
    }
}

Run dotblaze demo:event in a Blog application. The fake checks dispatch and suppresses listeners. For real listener execution, remove the fake/assertion and add a Listener<DocumentPreviewed> class whose Handle logs the document ID; application listeners are discovered automatically. See the complete broadcast event in PostCreated.cs and real queued-listener execution in QueueAdvancedTest.cs.

Introduction ​

Events let one part of the app announce that something happened ("an order shipped") without knowing who cares. Listeners react to it: send an email, update a report, clear a cache. An event can have many listeners, and listeners can run immediately or through the queue.

Defining Events ​

An event is any class or record carrying the data listeners need. Implementing the empty IEvent marker is optional but makes intent clear:

csharp
namespace App.Events;

public sealed record OrderShipped(Order Order) : IEvent;

Defining Listeners ​

A listener extends Listener<TEvent> and implements Handle. Its constructor can take any service registered in dependency injection:

csharp
namespace App.Listeners;

public class SendShipmentNotification(ILogger<SendShipmentNotification> logger) : Listener<OrderShipped>
{
    public override Task Handle(OrderShipped e)
    {
        logger.LogInformation("Order {Id} shipped", e.Order.Id);
        return Task.CompletedTask;
    }
}

Registering Listeners ​

There is nothing to register. Every Listener<T> class in the application assembly is discovered at startup, like Laravel's event discovery. A new listener instance is created for every event, in the current service scope.

Closure Listeners ​

Event.Listen registers a closure, sync or async. Register closures once at startup, in a service provider's Boot method:

csharp
public class AppServiceProvider : Provider
{
    public override void Boot(WebApplication app)
    {
        Event.Listen<OrderShipped>(e => Log.Info("Order {Id} shipped", e.Order.Id));

        Event.Listen<OrderShipped>(async e =>
        {
            await Http.Post("https://hooks.example.com/shipped", new { e.Order.Id });
        });
    }
}

NOTE

Closure listeners are kept for the lifetime of the application and are never removed. Calling Event.Listen inside a request or job adds another listener every time.

For each event type, class listeners run before closures. Listeners for the event's own type run before those for its base classes and interfaces.

Listening to Base Types and Interfaces ​

A listener for a base class or an interface also receives every event that derives from it or implements it. A listener for IEvent sees every event that uses the marker, including model events:

csharp
public class AuditEverything : Listener<IEvent>
{
    public override Task Handle(IEvent e)
    {
        Log.Debug("Event {Type}", e.GetType().Name);
        return Task.CompletedTask;
    }
}

Wildcard Listeners ​

Event.Listen(pattern, ...) matches events by name, with * as a wildcard. An event's name is its full type name; model events are named like Laravel's, eloquent.{event}: {model type}. The handler gets the name and the event:

csharp
Event.Listen("App.Events.Order*", (name, e) => Log.Info("{Event} dispatched", name));
Event.Listen("eloquent.deleted: *", async (name, e) => await Audit.Record(((IModelEvent)e).Model));

Event Subscribers ​

A subscriber registers several listeners from one class. DotBlaze finds classes that implement IEventSubscriber in your application, creates one instance at startup, and calls Subscribe:

Registered, Logout, and Welcome below are application-defined event/mailable types, not automatically dispatched authentication events. Define and dispatch them in your own authentication workflow if using this illustration.

csharp
public class UserEventSubscriber : IEventSubscriber
{
    public void Subscribe(EventSubscriptions events)
    {
        events.Listen<Registered>(HandleRegistered);
        events.Listen<Logout>(e => Log.Info("{Id} logged out", e.User.Id));
        events.Listen("eloquent.created: *", (name, e) => Task.CompletedTask);
    }

    Task HandleRegistered(Registered e) => Mail.To(e.User).Send(new Welcome { User = e.User });
}

Because the instance lives for the whole application, its constructor may only take singleton services; use facades inside the handlers.

Queued Event Listeners ​

Add IShouldQueue to a listener to run it through the queue instead of during the request:

csharp
public class GenerateInvoicePdf : Listener<OrderShipped>, IShouldQueue
{
    public override async Task Handle(OrderShipped e)
    {
        // runs in the queue worker
    }
}

When the event is dispatched, DotBlaze pushes an internal CallQueuedListener job, by default onto the default queue of the default connection. The event is serialized with the same rules as job payloads: models inside it are stored by id and fetched again when the listener runs, so the event's properties must be serializable to JSON. The worker then creates the listener with dependency injection and calls Handle.

With the sync queue driver, queued listeners run immediately.

Override these members to change how the listener is queued:

csharp
public class GenerateInvoicePdf : Listener<OrderShipped>, IShouldQueue
{
    public override string? Queue => "invoices";
    public override string? Connection => "redis";
    public override TimeSpan? Delay => TimeSpan.FromMinutes(1);
    public override int Tries => 3;
    public override int[] Backoff => [10, 60];
    public override bool AfterCommit => true;   // queue it only after the current transaction commits

    // Decide per event whether to queue the listener at all.
    public override bool ShouldQueue(OrderShipped e) => e.Order.Total > 0;

    public override Task Handle(OrderShipped e) { ... }

    // Called when the listener has failed its last attempt.
    public override Task Failed(OrderShipped e, Exception exception) { ... }
}

Dispatching Events ​

Await Event.Dispatch:

csharp
await Event.Dispatch(new OrderShipped(order));

Listeners run one after another, in the dispatching code's flow. An exception from a listener stops the remaining listeners and propagates to the caller.

Dispatching Events After Database Transactions ​

An event that implements IShouldDispatchAfterCommit waits until the current DB.Transaction commits, and is never dispatched if it rolls back. Without a transaction it is dispatched right away:

csharp
public sealed record OrderShipped(Order Order) : IShouldDispatchAfterCommit;

await DB.Transaction(async () =>
{
    await order.Update(new { Status = "shipped" });
    await Event.Dispatch(new OrderShipped(order));   // listeners run after the commit
});

DB.AfterCommit(callback) does the same for any code.

Model Events ​

Models dispatch Saving<T>, Saved<T>, Creating<T>, Created<T>, Updating<T>, Updated<T>, Deleting<T>, Deleted<T>, Restoring<T>, and Restored<T> through this same dispatcher, each with the model in its Model property. Listen to them like any other event, or with an observer:

csharp
public class WelcomeNewUser : Listener<Created<User>>, IShouldQueue
{
    public override async Task Handle(Created<User> e)
    {
        await new SendWelcomeEmail { User = e.Model, Subject = "Welcome!" }.Dispatch();
    }
}

See Model Events for when each one fires.

Framework Events ​

DotBlaze reports what it does internally through Instrumentation, like Laravel's DB::listen and Queue::after. Telescope, Pulse, and Horizon are built on these events, and you can listen to them yourself in a provider's Boot method:

csharp
Instrumentation.Listen<QueryExecuted>(query =>
{
    if (query.Duration > TimeSpan.FromSeconds(1))
        Log.Warning("Slow query ({Ms} ms): {Sql}", query.Duration.TotalMilliseconds, query.Sql);
});

Instrumentation.Listen<JobFailed>(job => Log.Error(job.Exception, "Job {Job} failed on {Queue}", job.Name, job.Queue));
EventWhen
RequestStarting, RequestHandledA request starts, and ends (with its duration and the exception that ended it, if any).
QueryExecutedA SQL command ran, from a model or the query builder (SQL, bindings, duration, connection).
JobQueued, JobProcessing, JobProcessed, JobReleased, JobFailedA job was pushed, picked up, finished, put back for a retry, or failed for good.
CommandStarting, CommandFinishedA console command starts and ends (with its exit code).
ScheduledTaskFinishedA scheduled task ran (with its exception, if it failed).
ExceptionReportedAn exception was reported.
CacheHit, CacheMissed, CacheKeyWritten, CacheKeyForgottenA cache read found a key or not, or a key was written or removed.
HttpClientRequestSentThe Http client got a response, or failed.
MailSent, NotificationSentA mail was sent, or a notification went out on a channel.
EventDispatchedAn event was dispatched with Event.Dispatch (not model events).
GateEvaluatedAn ability or policy was checked.

Unlike application events, framework events run their listeners right away, in the code that raised them, and do not go through Event.Fake(). Keep listeners quick: store what you need and do slow work, like writing to a database, later. An exception thrown by a listener is ignored, so a broken listener never breaks a request. Listen returns an IDisposable; dispose it to stop listening.

To run code without raising events, for example while writing your own monitoring data, wrap it in Instrumentation.Pause():

csharp
using (Instrumentation.Pause())
{
    await DB.Table("metrics").Insert(rows);
}

Testing ​

Event.Fake() records events without running any listener, including model events:

csharp
var events = Event.Fake();

var author = await Author.Create(new { Name = "A", Password = "x" });
author.Name = "B";
await author.Save();

events.AssertDispatched<Created<Author>>(e => e.Model.Id == author.Id);
events.AssertDispatched<Updated<Author>>(e => e.Model.Name == "B");
events.AssertNotDispatched<Deleted<Author>>();

See Fakes.