Attribute registration extension for Xer.Cqrs.CommandStack
Branch | Status |
---|---|
Master | |
Dev |
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:
To install Nuget packages:
- Open command prompt
- Go to project directory
- Add the packages to the project:
dotnet add package Xer.Cqrs.CommandStack.Extensions.Attributes
- Restore the packages:
dotnet restore
// 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);
}