SimpleMediator for .NET

repository·main·Indexed 41 days ago

https://github.com/netdevpack/simplemediator

A lightweight, in-process messaging library for .NET implementing the Mediator pattern. It decouples components using Requests (commands/queries) via IRequest<TResponse> and Notifications (events) via INotification, with support for automatic assembly scanning or manual dependency injection registration.

Tokens
1.5K
Snippets
5
Records
5
Agent score
1%

What's inside SimpleMediator

  1. How Requests and Notifications work in SimpleMediator

    main

    SimpleMediator uses two primary messaging patterns to decouple components:

    1. Requests (IRequest<TResponse>): Represents a command or query that expects a single response. You use IMediator.Send() to execute a request, which is handled by exactly one IRequestHandler<TRequest, TResponse>.

    2. Notifications (INotification): Represents an event broadcast to multiple handlers. You use IMediator.Publish() to broadcast a notification, which can be handled by zero or more INotificationHandler<TNotification> implementations.

    This separation allows you to distinguish between actions that change state and return a result (Commands/Queries) and actions that simply communicate that something has occurred (Events).

    // A Request (Command/Query) that returns a string
    public class CreateCustomerCommand : IRequest<string>
    {
        public string Name { get; set; }
    }
    
    // A Notification (Event)
    public class CustomerCreatedEvent : INotification
    {
        public Guid CustomerId { get; }
        public CustomerCreatedEvent(Guid customerId) => CustomerId = customerId;
    }
  2. Register SimpleMediator in Dependency Injection

    main

    You can register SimpleMediator and its handlers in your service collection using two methods:

    Automatic Registration (Assembly Scanning)

    Use AddSimpleMediator() to automatically scan assemblies and register all discovered handlers.

    Manual Registration

    For full control, register the mediator and each handler individually.

    Note: SimpleMediator requires Microsoft.Extensions.DependencyInjection.Abstractions.

    // Automatic registration via assembly scanning
    services.AddSimpleMediator();
    
    // OR Manual registration
    services.AddSingleton<IMediator, Mediator>();
    services.AddTransient<IRequestHandler<CreateCustomerCommand, string>, CreateCustomerHandler>();
    services.AddTransient<INotificationHandler<CustomerCreatedEvent>, SendWelcomeEmailHandler>();
  3. Execute messages using IMediator

    main

    Once registered, inject IMediator into your services to send requests or publish notifications.

    public class CustomerAppService
    {
        private readonly IMediator _mediator;
    
        public CustomerAppService(IMediator mediator)
        {
            _mediator = mediator;
        }
    
        public async Task<string> CreateCustomer(string name)
        {
            // Sends the command and waits for the response from the handler
            return await _mediator.Send(new CreateCustomerCommand { Name = name });
        }
    }
  4. Implement Request and Notification Handlers

    main

    To process messages, implement the corresponding handler interfaces.

    • For IRequest<T>, implement IRequestHandler<TRequest, TResponse>.
    • For INotification, implement INotificationHandler<TNotification>.

    Handlers are typically registered in your Dependency Injection container.

    // Request Handler
    public class CreateCustomerHandler : IRequestHandler<CreateCustomerCommand, string>
    {
        private readonly IMediator _mediator;
    
        public CreateCustomerHandler(IMediator mediator) => _mediator = mediator;
    
        public async Task<string> Handle(CreateCustomerCommand request, CancellationToken cancellationToken)
        {
            var id = Guid.NewGuid();
            // Publish an event after successful command execution
            await _mediator.Publish(new CustomerCreatedEvent(id), cancellationToken);
            return $"Customer '{request.Name}' created with ID {id}";
        }
    }
    
    // Notification Handler
    public class SendWelcomeEmailHandler : INotificationHandler<CustomerCreatedEvent>
    {
        public Task Handle(CustomerCreatedEvent notification, CancellationToken cancellationToken)
        {
            Console.WriteLine($"Sending welcome email to customer {notification.CustomerId}");
            return Task.CompletedTask;
        }
    }