Event-Driven Architecture with RCommon
Event-driven architecture decouples components by having them communicate through events rather than direct calls. Producers emit events without knowing which consumers exist. Consumers react to events without knowing which producer emitted them. RCommon provides a consistent IEventProducer / ISubscriber<T> abstraction over in-process buses (InMemoryEventBus, MediatR) and distributed brokers (MassTransit, Wolverine).
When to Use This Approach
Use event-driven design with RCommon when:
- Side effects (sending email, updating a read model, audit logging) should not be tangled into command handlers
- You want to scale event consumers independently from producers
- Components must remain decoupled so they can evolve at different rates
- You need reliable delivery guarantees provided by a message broker
Core Concepts
Events
An event represents something that happened. It is named in the past tense and is immutable after construction:
using RCommon.Models.Events;
// An in-process domain event
public class LeaveRequestApprovedEvent : ISyncEvent
{
public LeaveRequestApprovedEvent() { }
public LeaveRequestApprovedEvent(int leaveRequestId, string employeeId)
{
LeaveRequestId = leaveRequestId;
EmployeeId = employeeId;
}
public int LeaveRequestId { get; }
public string EmployeeId { get; }
}
ISyncEvent is the base marker interface. All event types in RCommon derive from it.
Producers
A producer publishes an event to one or more subscribers. At the call site, you depend on IEventProducer:
public class ApproveLeaveRequestCommandHandler
: IAppRequestHandler<ApproveLeaveRequestCommand, BaseCommandResponse>
{
private readonly IGraphRepository<LeaveRequest> _repository;
private readonly IEnumerable<IEventProducer> _eventProducers;
public ApproveLeaveRequestCommandHandler(
IGraphRepository<LeaveRequest> repository,
IEnumerable<IEventProducer> eventProducers)
{
_repository = repository;
_eventProducers = eventProducers;
}
public async Task<BaseCommandResponse> HandleAsync(
ApproveLeaveRequestCommand request,
CancellationToken cancellationToken)
{
var leaveRequest = await _repository.FindAsync(request.Id);
leaveRequest.Approved = true;
await _repository.UpdateAsync(leaveRequest);
var @event = new LeaveRequestApprovedEvent(leaveRequest.Id,
leaveRequest.RequestingEmployeeId);
foreach (var producer in _eventProducers)
{
await producer.ProduceEventAsync(@event);
}
return new BaseCommandResponse { Success = true };
}
}
Subscribers
A subscriber reacts to a specific event type. It implements ISubscriber<TEvent>:
public class SendApprovalEmailHandler : ISubscriber<LeaveRequestApprovedEvent>
{
private readonly IEmailService _emailService;
public SendApprovalEmailHandler(IEmailService emailService)
{
_emailService = emailService;
}
public async Task HandleAsync(
LeaveRequestApprovedEvent notification,
CancellationToken cancellationToken = default)
{
await _emailService.SendAsync(new EmailRequest
{
To = notification.EmployeeId,
Subject = "Leave Request Approved",
Body = $"Your leave request #{notification.LeaveRequestId} has been approved."
});
}
}
Event Handling Providers
RCommon ships with four event handling providers. You choose one (or more) at startup via the fluent builder.
WithEventHandling<T> is cache-aware. In a modular codebase, each feature module can call services.AddRCommon().WithEventHandling<InMemoryEventBusBuilder>(eh => eh.AddSubscriber<MyEvent, MyHandler>()) independently — the cached InMemoryEventBusBuilder is reused across modules and subscriber/producer registrations accumulate. AddProducer<T> deduplicates by concrete producer type, so the same producer registered from two modules yields exactly one descriptor. This pattern works for InMemoryEventBusBuilder, MediatREventHandlingBuilder, and WolverineEventHandlingBuilder; MassTransitEventHandlingBuilder has a known cross-module limitation documented on its MassTransit page. See Modular Composition for the full conflict matrix.
In-Memory Event Bus
The simplest provider. Events are dispatched synchronously within the same process. No external broker required. Best for domain events within a single service.
services.AddRCommon()
.WithEventHandling<InMemoryEventBusBuilder>(eventHandling =>
{
eventHandling.AddProducer<PublishWithEventBusEventProducer>();
eventHandling.AddSubscriber<LeaveRequestApprovedEvent, SendApprovalEmailHandler>();
});
MediatR
Uses MediatR's notification pipeline. Integrates with existing MediatR configurations and supports MediatR pipeline behaviors:
services.AddRCommon()
.WithEventHandling<MediatREventHandlingBuilder>(eventHandling =>
{
eventHandling.AddProducer<PublishWithMediatREventProducer>();
eventHandling.AddSubscriber<LeaveRequestApprovedEvent, SendApprovalEmailHandler>();
});
MassTransit
Durable, distributed messaging. Supports RabbitMQ, Azure Service Bus, Amazon SQS, and others. Events survive process restarts and can be delivered to subscribers in separate services:
services.AddRCommon()
.WithEventHandling<MassTransitEventHandlingBuilder>(eventHandling =>
{
eventHandling.UsingRabbitMq((context, cfg) =>
{
cfg.Host("rabbitmq://localhost");
cfg.ConfigureEndpoints(context);
});
eventHandling.AddProducer<PublishWithMassTransitEventProducer>();
eventHandling.AddSubscriber<LeaveRequestApprovedEvent, SendApprovalEmailHandler>();
});
For development and testing, use the in-memory transport instead of RabbitMQ:
eventHandling.UsingInMemory((context, cfg) =>
{
cfg.ConfigureEndpoints(context);
});
Wolverine
Wolverine focuses on high throughput and local queue processing:
// In Program.cs, before services.AddRCommon()
builder.Host.UseWolverine(options =>
{
options.LocalQueue("leave-events");
});
services.AddRCommon()
.WithEventHandling<WolverineEventHandlingBuilder>(eventHandling =>
{
eventHandling.AddProducer<PublishWithWolverineEventProducer>();
eventHandling.AddSubscriber<LeaveRequestApprovedEvent, SendApprovalEmailHandler>();
});