Mediator Class
Definition
- Namespace
- Savvyio.Extensions
- Assemblies
- Savvyio.Extensions.Dispatchers.dll
Provides a default implementation of the IMediator interface.
public class Mediator : IMediator, ICommandDispatcher, IDomainEventDispatcher, IIntegrationEventDispatcher, IQueryDispatcher, IDispatcher
- Inheritance
-
objectMediator
- Implements
- Extension Methods
Examples
Mediator is the single-entry-point dispatcher that routes commands, queries, and events to their handlers without requiring separate dispatcher injections. Create it with a ServiceLocator that resolves handlers by service type.
using System;
using System.Collections.Generic;
using Savvyio;
using Savvyio.Commands;
using Savvyio.Dispatchers;
using Savvyio.Extensions;
using Savvyio.Handlers;
namespace ExampleApp;
public sealed class MediatorExample
{
public void Dispatch()
{
var handler = new CreateOrderHandler();
var locator = new ServiceLocator(serviceType =>
serviceType == typeof(ICommandHandler) ? new object[] { handler } : Array.Empty<object>());
var mediator = new Mediator(locator);
mediator.Commit(new CreateOrderCommand("SO-42"));
Console.WriteLine($"Processed orders: {handler.ProcessedOrders.Count}");
}
}
public sealed class CreateOrderHandler : ICommandHandler
{
public List<string> ProcessedOrders { get; } = new();
public IFireForgetActivator<ICommand> Delegates =>
HandlerFactory.CreateFireForget<ICommand>(r =>
r.Register<CreateOrderCommand>(cmd => ProcessedOrders.Add(cmd.OrderId)));
}
public sealed record CreateOrderCommand(string OrderId) : Request, ICommand;
Constructors
| Name | Description |
|---|---|
| Mediator(IServiceLocator) | Initializes a new instance of the Mediator class. |
Methods
| Name | Description |
|---|---|
| Commit(ICommand) | Commits the specified |
| CommitAsync(ICommand, Action<AsyncOptions>) | Commits the specified |
| Publish(IIntegrationEvent) | Publishes the specified |
| PublishAsync(IIntegrationEvent, Action<AsyncOptions>) | Publishes the specified |
| QueryAsync<TResult>(IQuery<TResult>, Action<AsyncOptions>) | Queries the specified |
| Query<TResult>(IQuery<TResult>) | Queries the specified |
| Raise(IDomainEvent) | Raises the specified |
| RaiseAsync(IDomainEvent, Action<AsyncOptions>) | Raises the specified |