MemoryEventBus.InMemory
1.0.0
dotnet add package MemoryEventBus.InMemory --version 1.0.0
NuGet\Install-Package MemoryEventBus.InMemory -Version 1.0.0
<PackageReference Include="MemoryEventBus.InMemory" Version="1.0.0" />
<PackageVersion Include="MemoryEventBus.InMemory" Version="1.0.0" />
<PackageReference Include="MemoryEventBus.InMemory" />
paket add MemoryEventBus.InMemory --version 1.0.0
#r "nuget: MemoryEventBus.InMemory, 1.0.0"
#:package MemoryEventBus.InMemory@1.0.0
#addin nuget:?package=MemoryEventBus.InMemory&version=1.0.0
#tool nuget:?package=MemoryEventBus.InMemory&version=1.0.0
MemoryEventBus - High-Performance In-Memory Event Bus
Visão Geral
Uma implementação customizada de Event Bus baseada em System.Threading.Channels que oferece performance superior ao MediatR para cenários de alta throughput, com funcionalidades opcionais avançadas.
Funcionalidades Implementadas
Versão Básica (Funcional)
- Event Channel Manager - Gerenciamento de channels com
ConcurrentDictionary - Producers/Consumers - Publicação e consumo assíncrono de eventos
- Domain Events - Implementação baseada em DDD
- Performance Otimizada - Usando
Channel.CreateUnboundedpara alta performance
Funcionalidades Avançadas (Opcionais)
- Error Handling Centralizado -
IEventBusErrorHandlereDefaultEventBusErrorHandler - Retry Policies -
ExponentialBackoffRetryPolicyeLinearRetryPolicy - Metrics/Observability - Usando
System.Diagnostics.Metrics(.NET 8) - Backpressure Handling - Suporte a bounded channels
Como Usar
Configuração Básica (Recomendada para começar)
No appsettings.json:
{
"EventBus": {
"UseEnhancedFeatures": false
}
}
Configuração Avançada (Com todas as funcionalidades)
No appsettings.json:
{
"EventBus": {
"UseEnhancedFeatures": true,
"DefaultChannelCapacity": 1000,
"UseBoundedChannels": false,
"DefaultMaxRetryAttempts": 3,
"DefaultRetryBaseDelayMs": 100,
"DefaultRetryMaxDelayMs": 30000
}
}
Arquitetura
??????????????????? ???????????????????? ???????????????????
? Producer ?????? EventChannel ?????? Consumer ?
? ? ? Manager ? ? ?
??????????????????? ???????????????????? ???????????????????
? ? ?
? ? ?
??????????????????? ???????????????????? ???????????????????
? Error Handler ? ? Metrics ? ? Retry Policy ?
? ? ? ? ? ?
??????????????????? ???????????????????? ???????????????????
Performance vs MediatR
| Métrica | MemoryEventBus | MediatR |
|---|---|---|
| Throughput | ~10-50x maior | Baseline |
| Latência | Muito baixa | Baixa |
| Memory | Menor overhead | Maior overhead |
| Reflection | Mínima | Extensiva |
Exemplo de Uso
1. Publicar um Evento
[HttpPost("process-payment")]
public async Task<IActionResult> ProcessPaymentAsync([FromQuery] decimal amount)
{
var order = await _payUseCase.ExecuteAsync(amount);
return order is null ? BadRequest("Payment processing failed.") : Ok(order);
}
2. Implementar um Consumer
public class StockReducerConsumer : BackgroundService
{
private readonly Channel<DomainEvent> _channel;
public StockReducerConsumer(IEventChannelManager channelManager)
{
_channel = channelManager.GetOrCreateChannel<OrderPaidEvent>();
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await foreach (var domainEvent in _channel.Reader.ReadAllAsync(stoppingToken))
{
if (domainEvent is OrderPaidEvent orderPaidEvent)
{
// Processar evento
await ProcessEventAsync(orderPaidEvent, stoppingToken);
}
}
}
}
Melhorias Implementadas
1. Error Handling Centralizado
public async Task HandleErrorAsync<TEvent>(TEvent @event, Exception exception, int attemptNumber, CancellationToken cancellationToken = default)
2. Retry Policies
- ExponentialBackoffRetryPolicy: Delay exponencial entre tentativas
- LinearRetryPolicy: Delay fixo entre tentativas
3. Metrics/Observability
- Contadores de eventos publicados/consumidos/falhados
- Histograma de tempo de processamento
- Gauge de profundidade dos channels
4. Backpressure Handling
public Channel<DomainEvent> GetOrCreateBoundedChannel<TEvent>(int capacity) where TEvent : DomainEvent
Conclusão
Esta implementação oferece uma alternativa de alta performance ao MediatR, especialmente adequada para:
- Microsserviços de alta throughput
- Sistemas com requisitos rigorosos de latência
- Cenários onde controle fino sobre o processamento é necessário
- Aplicações que precisam de observabilidade detalhada
Para projetos que requerem funcionalidades mais complexas de pipeline (validação, autorização, etc.), o MediatR ainda pode ser mais apropriado.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. 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. |
-
net8.0
- MemoryEventBus.Abstractions (>= 1.0.0)
- Microsoft.Extensions.Diagnostics.HealthChecks.Abstractions (>= 9.0.0)
- Microsoft.Extensions.Hosting.Abstractions (>= 9.0.10)
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 | 300 | 11/8/2025 |