Skip to content

XerProjects/Xer.Cqrs.EventStack.Extensions.Attributes

Repository files navigation

Xer.Cqrs.EventStack.Extensions.Attributes

Attribute registration extension for Xer.Cqrs.EventStack

Build

Branch Status
Master Build status
Dev Build status

Nuget

NuGet

Installation

You can simply clone this repository, build the source, reference the dll from the project, and code away!

Xer.Cqrs.EventStack.Extensions.Attributes library is available as a Nuget package:

NuGet

To install Nuget packages:

  1. Open command prompt
  2. Go to project directory
  3. Add the packages to the project:
    dotnet add package Xer.Cqrs.EventStack.Extensions.Attributes
  4. Restore the packages:
    dotnet restore

Event Handler Attribute Registration

// Example event.
public class ProductRegisteredEvent
{
    public int ProductId { get; }
    public string ProductName { get; }

    public ProductRegisteredEvent(int productId, string productName)
    {
        ProductId = productId;
        ProductName = productName;
    }
}

// Example event handlers.
public class ProductRegisteredEventHandlers : IEventHandler<ProductRegisteredEvent>
{
    // Sync event handler.
    [EventHandler]
    public void Handle(ProductRegisteredEvent @event)
    {
        System.Console.WriteLine($"ProductRegisteredEventHandler handled {@event.GetType()}.");
    }
    
    // Async event handler.
    [EventHandler]
    public Task SendEmailNotificationAsync(ProductRegisteredEvent @event, CancellationToken ct)
    {
        System.Console.WriteLine($"Sending email notification...");
        return Task.CompletedTask;
    }
}
// Event Handler Registration.
public EventDelegator RegisterEventHandlers()
{
    // MultiMessageHandlerRegistration allows registration of a multiple message handlers per message type.
    var registration = new MultiMessageHandlerRegistration();

    // Register all methods with [EventHandler] attribute.
    registration.RegisterEventHandlerAttributes(() => new ProductRegisteredEventHandlers(new ProductRepository());

    // Build the event delegator.
    IMessageHandlerResolver resolver = registration.BuildMessageHandlerResolver();
    return new EventDelegator(resolver);
}