Skip to content

Notifications

ferdi kurnaz edited this page Sep 1, 2026 · 1 revision

Notifications (Pub/Sub)

Notifications let you broadcast an event to multiple handlers. This is useful when one action should trigger several side effects.

Defining a Notification

public record ProductCreatedEvent(int ProductId, string ProductName) : INotification;

Defining Handlers

You can create as many handlers as you need for the same notification. All of them will run when the notification is published.

// Handler A - Send Email
public class EmailNotificationHandler : INotificationHandler<ProductCreatedEvent>
{
    public async Task Handle(ProductCreatedEvent notification, CancellationToken cancellationToken)
    {
        // Send email logic...
        await Task.CompletedTask;
    }
}

// Handler B - Write a log entry (example of a second handler)
public class LoggingNotificationHandler : INotificationHandler<ProductCreatedEvent>
{
    public async Task Handle(ProductCreatedEvent notification, CancellationToken cancellationToken)
    {
        // Logging logic...
        await Task.CompletedTask;
    }
}

Publishing a Notification

await _mediator.PublishAsync(new ProductCreatedEvent(42, "Laptop"));

Both EmailNotificationHandler and LoggingNotificationHandler will run automatically.

When to Use Notifications vs Requests

Use a Request when... Use a Notification when...
You need a single, direct answer. You want to inform many parts of the app about something that happened.
Only one handler should run. Zero, one, or many handlers can react.
Example: CreateProductCommand Example: ProductCreatedEvent

Next: Dependency Injection Setup

Clone this wiki locally