Table of Contents

Mediator Class

Definition

Namespace
Savvyio.Extensions
Assemblies
Savvyio.Extensions.Dispatchers.dll
Source
src/Savvyio.Extensions.Dispatchers/Mediator.cs

Provides a default implementation of the IMediator interface.

public class Mediator : IMediator, ICommandDispatcher, IDomainEventDispatcher, IIntegrationEventDispatcher, IQueryDispatcher, IDispatcher
Inheritance
object
Mediator
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 request using Fire-and-Forget/In-Only MEP.

CommitAsync(ICommand, Action<AsyncOptions>)

Commits the specified request asynchronous using Fire-and-Forget/In-Only MEP.

Publish(IIntegrationEvent)

Publishes the specified request using Fire-and-Forget/In-Only MEP.

PublishAsync(IIntegrationEvent, Action<AsyncOptions>)

Publishes the specified request asynchronous using Fire-and-Forget/In-Only MEP.

QueryAsync<TResult>(IQuery<TResult>, Action<AsyncOptions>)

Queries the specified request asynchronous using Request-Reply/In-Out MEP.

Query<TResult>(IQuery<TResult>)

Queries the specified request using Request-Reply/In-Out MEP.

Raise(IDomainEvent)

Raises the specified request using Fire-and-Forget/In-Only MEP.

RaiseAsync(IDomainEvent, Action<AsyncOptions>)

Raises the specified request using Fire-and-Forget/In-Only MEP.

See Also