WaiterMediator.Extensions.Queues 1.0.0

dotnet add package WaiterMediator.Extensions.Queues --version 1.0.0
                    
NuGet\Install-Package WaiterMediator.Extensions.Queues -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="WaiterMediator.Extensions.Queues" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="WaiterMediator.Extensions.Queues" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="WaiterMediator.Extensions.Queues" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add WaiterMediator.Extensions.Queues --version 1.0.0
                    
#r "nuget: WaiterMediator.Extensions.Queues, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package WaiterMediator.Extensions.Queues@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=WaiterMediator.Extensions.Queues&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=WaiterMediator.Extensions.Queues&version=1.0.0
                    
Install as a Cake Tool

WaiterMediator.Extensions.Queues

Fila de Domain Events baseada em System.Threading.Channels integrada ao WaiterMediator. Objetivo: enfileirar INotification para processamento em background por um worker que publica eventos via IWaiter.

Principais componentes e responsabilidades

  • DomainEventQueue

    • Implementa uma fila baseada em Channel<INotification>.
    • EnqueueAsync(INotification) para enfileiramento assíncrono.
    • Reader expõe ChannelReader<INotification> para consumo.
  • DomainEventWorker

    • BackgroundService que consome DomainEventQueue.Reader e chama IWaiter.Publish(notification, ct) para cada item.
  • AddDomainEventQueue (extensão de DI)

    • Registra DomainEventQueue como singleton.
    • Mapeia IDomainEventQueue para a instância singleton.
    • Adiciona DomainEventWorker como HostedService.

Requisitos técnicos

  • .NET 10.0
  • WaiterMediator.Abstractions
  • Microsoft.Extensions.Hosting
  • Microsoft.Extensions.DependencyInjection

Instalação

Via dotnet CLI:

dotnet add package WaiterMediator.Extensions.Queues

Registro no DI

Exemplo mínimo de registro:

// Program.cs
builder.Services.AddWaiter(typeof(Program).Assembly);
builder.Services.AddDomainEventQueue();

Exemplos de eventos e handlers

Evento:

public record UserCreatedEvent(int UserId) : INotification;

Handler síncrono:

public class UserCreatedHandler : INotificationHandler<UserCreatedEvent>
{
    public Task Handle(UserCreatedEvent notification, CancellationToken cancellationToken)
    {
        Console.WriteLine($"UserCreated: {notification.UserId}");
        return Task.CompletedTask;
    }
}

Handler assíncrono:

public class UserCreatedAsyncHandler : INotificationHandler<UserCreatedEvent>
{
    public async Task Handle(UserCreatedEvent notification, CancellationToken cancellationToken)
    {
        await Task.Delay(100, cancellationToken);
        Console.WriteLine($"Processed async: {notification.UserId}");
    }
}

Exemplo de enfileiramento (produtor)

// produtor: enfileira um domain event
await domainEventQueue.EnqueueAsync(new UserCreatedEvent(42));

Observação: o DomainEventWorker consome a fila e chama IWaiter.Publish(notification, ct), que resolve e executa os handlers registrados.

Exemplo completo mínimo de Program.cs

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

return Host.CreateDefaultBuilder(args)
    .ConfigureServices((context, services) =>
    {
        services.AddWaiter(typeof(Program).Assembly);
        services.AddDomainEventQueue();
        // registrar demais serviços
    })
    .RunConsoleAsync();

Boas práticas e considerações

  • Idempotência: handlers devem ser idempotentes; eventos podem ser reprocessados.
  • Canais bounded vs unbounded: prefira bounded para controlar memória e aplicar backpressure; unbounded simplifica mas pode consumir muita memória em picos.
  • Retry e observability: aplicar políticas de retry/exponential backoff quando apropriado; expor métricas (tamanho da fila, latência, falhas).
  • Ordem e concorrência: um worker preserva ordem; múltiplos consumidores aumentam concorrência e podem alterar ordem.

API resumida

  • DomainEventQueue

    • ValueTask EnqueueAsync(INotification domainEvent)
    • ChannelReader<INotification> Reader
  • DomainEventWorker

    • BackgroundService que consome Reader e chama IWaiter.Publish
  • AddDomainEventQueue()

    • Extensão IServiceCollection que registra DomainEventQueue (singleton), mapeia IDomainEventQueue e adiciona o hosted service

Debug / Desenvolvimento

  • Habilitar logs do host para acompanhar o worker.
  • Em testes, injetar IWaiter mock/spy para verificar Publish.
  • Instrumentar métricas básicas (tamanho da fila, taxa de consumo) para diagnóstico.

Contribuição

Fluxo recomendado:

  1. Fork → criar branch feature/x ou fix/x.
  2. Implementar mudança com testes automatizados.
  3. Abrir Pull Request com descrição e impacto.

Licença e autor

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 453 12/9/2025