Table of Contents

InMemoryEventBus Class

Definition

Namespace
Savvyio.EventDriven.Messaging
Assemblies
Savvyio.EventDriven.Messaging.dll
Source
src/Savvyio.EventDriven.Messaging/InMemoryEventBus.cs

Provides an in-memory implementation of the IPublishSubscribeChannel<TRequest> interface useful for unit testing and the likes thereof.

public class InMemoryEventBus : IPublishSubscribeChannel<IIntegrationEvent>, IPublisher<IIntegrationEvent>, ISubscriber<IIntegrationEvent>
Inheritance
InMemoryEventBus
Implements

Examples

InMemoryEventBus publishes and drains IMessage<IIntegrationEvent> envelopes in the same process without a real broker, making it the test-time substitute for NATS, RabbitMQ, or Azure Queue Storage. The setup requires an integration event wrapped in IMessage<IIntegrationEvent> via IntegrationEventExtensions.ToMessage; after PublishAsync, call SubscribeAsync to drain the internal queue and receive the delivered payloads. The expected outcome is that the subscriber callback fires with the original event data so you can assert message-level behavior in isolation.

using System;
using System.Threading.Tasks;
using Savvyio.EventDriven;
using Savvyio.EventDriven.Messaging;
using Savvyio.Messaging;

namespace ExampleApp.InMemoryEventBusSample;

public sealed class InMemoryEventBusUsage
{
    public InMemoryEventBusUsage()
    {
        RunAsync().GetAwaiter().GetResult();
    }

    public string DeliveredEmailAddress { get; private set; } = string.Empty;

    private async Task RunAsync()
    {
        var bus = new InMemoryEventBus();
        IMessage<IIntegrationEvent> message = new MemberInvitedEventBusMessage("jane@example.com")
            .ToMessage(new Uri("https://api.example.com/invitations"), nameof(MemberInvitedEventBusMessage));

        await bus.PublishAsync(message);
        await bus.SubscribeAsync((received, _) =>
        {
            if (received.Data is MemberInvitedEventBusMessage invited)
            {
                DeliveredEmailAddress = invited.EmailAddress;
            }

            return Task.CompletedTask;
        });
    }
}

public sealed record MemberInvitedEventBusMessage(string EmailAddress) : IntegrationEvent;

Methods

Name Description
PublishAsync(IMessage<IIntegrationEvent>, Action<AsyncOptions>)

Publishes the specified event asynchronous using Publish-Subscribe Channel/Pub-Sub MEP.

SubscribeAsync(Func<IMessage<IIntegrationEvent>, CancellationToken, Task>, Action<SubscribeAsyncOptions>)

Subscribe to one or more event(s) asynchronous using Publish-Subscribe Channel/Pub-Sub MEP.