Skip to content

XerProjects/Xer.Cqrs.CommandStack.Extensions.Attributes

Repository files navigation

Xer.Cqrs.CommandStack.Extensions.Attributes

Attribute registration extension for Xer.Cqrs.CommandStack

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.CommandStack.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.CommandStack.Extensions.Attributes
  4. Restore the packages:
    dotnet restore

Command Handler Attribute Registration

// Example command.
public class RegisterProductCommand
{
    public int ProductId { get; }
    public string ProductName { get; }

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

// Example Command handler.
public class RegisterProductCommandHandler : ICommandAsyncHandler<RegisterProductCommand>
{
    private readonly IProductRepository _productRepository;

    public RegisterProductCommandHandler(IProductRepository productRepository)
    {
        _productRepository = productRepository;
    }

    [CommandHandler] // This is in Xer.Cqrs.CommandStack.Extensions.Attributes. This allows the method to registered as a command handler through attribute registration.
    public Task HandleAsync(RegisterProductCommand command, CancellationToken cancellationToken = default(CancellationToken))
    {
        return _productRepository.SaveAsync(new Product(command.ProductId, command.ProductName));
    }
}
// Command Handler Registration
public CommandDelegator RegisterCommandHandlers()
{            
    // SingleMessageHandlerRegistration only allows registration of a single message handler per message type.
    var registration = new SingleMessageHandlerRegistration();
    
    // Register methods with [CommandHandler] attribute.
    registration.RegisterCommandHandlerAttributes(() => new RegisterProductCommandHandler(new ProductRepository()));

    // Build command delegator.
    IMessageHandlerResolver resolver = registration.BuildMessageHandlerResolver();
    return new CommandDelegator(resolver);
}