MemoryEventBus.InMemory 1.0.0

dotnet add package MemoryEventBus.InMemory --version 1.0.0
                    
NuGet\Install-Package MemoryEventBus.InMemory -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="MemoryEventBus.InMemory" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="MemoryEventBus.InMemory" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="MemoryEventBus.InMemory" />
                    
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 MemoryEventBus.InMemory --version 1.0.0
                    
#r "nuget: MemoryEventBus.InMemory, 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 MemoryEventBus.InMemory@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=MemoryEventBus.InMemory&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=MemoryEventBus.InMemory&version=1.0.0
                    
Install as a Cake Tool

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.CreateUnbounded para alta performance

Funcionalidades Avançadas (Opcionais)

  • Error Handling Centralizado - IEventBusErrorHandler e DefaultEventBusErrorHandler
  • Retry Policies - ExponentialBackoffRetryPolicy e LinearRetryPolicy
  • 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 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. 
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 300 11/8/2025