Event / Notifications
In-Process Pub/Sub Notifications
If you'd like to take an event driven approach to building your application, you have the option to publish events from your endpoint handlers and have completely decoupled event-handlers to take action when events are published.
It's a simple 3 step process to do event driven work.
1. Define an Event Model/ DTO
This is the data contract that will be communicated across processes.
public class OrderCreatedEvent
{
public string OrderID { get; set; }
public string CustomerName { get; set; }
public decimal OrderTotal { get; set; }
}
2. Define an Event Handler
This is the code that will be fired/executed when events of the above DTO type gets published.
public class OrderCreationHandler : FastEventHandler<OrderCreatedEvent>
{
public override Task HandleAsync(OrderCreatedEvent eventModel, CancellationToken ct)
{
var logger = Resolve<ILogger<OrderCreationHandler>>();
logger.LogInformation($"order created event received:[{eventModel.OrderID}]");
return Task.CompletedTask;
}
}
3. Publish The Event
Simply hand in an event model/dto to the PublishAsync() method.
public class CreateOrderEndpoint : Endpoint<CreateOrderRequest>
{
public override void Configure()
{
Post("/sales/orders/create");
}
public override async Task HandleAsync(CreateOrderRequest req, CancellationToken ct)
{
var orderID = await orderRepo.CreateNewOrder(req);
await PublishAsync(new OrderCreatedEvent
{
OrderID = orderID,
CustomerName = req.Customer,
OrderTotal = req.OrderValue
});
await SendOkAsync();
}
}
The PublishAsync() Method
The PublishAsync() method has an overload that will take a Mode enum that lets you specify whether to wait for all subscribers to finish; wait for any subscriber to finish; or wait for none of the subscribers to finish.
For example, you can publish an event in a fire-n-forget manner with the following:
await PublishAsync(eventModel, Mode.WaitForNone);
The default mode is Mode.WaitForAll which will await all subscribers. i.e. execution will only continue after each and every subscriber of the event has completed their work.
Publishing From Event Handlers
It is also possible to publish events from within event handlers themselves like so:
public class OrderCreationHandler : FastEventHandler<OrderCreatedEvent>
{
public override async Task HandleAsync(OrderCreatedEvent eventModel, CancellationToken ct)
{
await PublishAsync(new ReOrderLevelReachedEvent
{
ItemId = "ITM-0001",
CurrentLevel = 5,
});
}
}