Vali-Mediator 1.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Vali-Mediator --version 1.0.0
                    
NuGet\Install-Package Vali-Mediator -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Vali-Mediator" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Vali-Mediator" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Vali-Mediator" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Vali-Mediator --version 1.0.0
                    
#r "nuget: Vali-Mediator, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Vali-Mediator@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Vali-Mediator&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Vali-Mediator&version=1.0.0
                    
Install as a Cake Tool

Vali-Mediator - Lightweight Mediator Pattern for .NET

Introduction 🚀

Welcome to Vali-Mediator, a lightweight .NET library that implements the Mediator pattern with CQRS support. Designed to simplify request handling, pipeline behaviors, and event notifications, Vali-Mediator offers a fluent and extensible API. It integrates seamlessly with dependency injection, making it perfect for managing commands, queries, and notifications in your .NET applications.

Installation 📦

To add Vali-Mediator to your .NET project, install it via NuGet with the following command:

dotnet add package Vali-Mediator

Ensure your project targets a compatible .NET version (e.g., .NET 7.0, 8.0, or 9.0). Vali-Mediator is lightweight and depends only on Microsoft.Extensions.DependencyInjection.Abstractions, ensuring easy integration into any .NET application.

Usage 🛠️

Vali-Mediator enables you to send requests to handlers and publish notifications to multiple subscribers through the IValiMediator interface. It supports pipeline behaviors (e.g., validation, logging) and leverages dependency injection for service resolution.

Configuration Example

Configure Vali-Mediator in your application’s startup (e.g., Program.cs in ASP.NET Core):

using Microsoft.Extensions.DependencyInjection;
using Vali_Mediator.Core.General.Extension;

var builder = WebApplication.CreateBuilder(args);

// Add Vali-Mediator services
builder.Services.AddValiMediator(config =>
{
    // Register assembly containing handlers and notifications
    config.RegisterServicesFromAssembly(typeof(Program).Assembly);
    // Add a pipeline behavior (e.g., validation)
    config.AddBehavior(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
});

var app = builder.Build();
app.Run();

Basic Example: Sending a Request

Define a request and its handler, then send it using the mediator:

using Vali_Mediator.Core.Request;
using Vali_Mediator.Core.General.Mediator;

// Define a request
public class CreateProductCommand : IRequest<int>
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

// Define the handler
public class CreateProductCommandHandler : IRequestHandler<CreateProductCommand, int>
{
    public Task<int> Handle(CreateProductCommand request, CancellationToken cancellationToken)
    {
        // Simulate saving to a database and returning an ID
        return Task.FromResult(42);
    }
}

// Usage in a controller or service
public class ProductService
{
    private readonly IValiMediator _mediator;

    public ProductService(IValiMediator mediator)
    {
        _mediator = mediator;
    }

    public async Task<int> CreateProduct(string name, decimal price)
    {
        var command = new CreateProductCommand { Name = name, Price = price };
        return await _mediator.Send(command);
    }
}

Basic Example: Publishing a Notification

Define a notification and its handler, then publish it:

using Vali_Mediator.Core.Notification;
using Vali_Mediator.Core.General.Mediator;

// Define a notification
public class ProductCreatedNotification : INotification
{
    public int ProductId { get; set; }
}

// Define a handler
public class ProductCreatedLogger : INotificationHandler<ProductCreatedNotification>
{
    public Task Handle(ProductCreatedNotification notification, CancellationToken cancellationToken)
    {
        Console.WriteLine($"Product {notification.ProductId} created.");
        return Task.CompletedTask;
    }
}

// Usage
public class ProductService
{
    private readonly IValiMediator _mediator;

    public ProductService(IValiMediator mediator)
    {
        _mediator = mediator;
    }

    public async Task NotifyProductCreated(int productId)
    {
        var notification = new ProductCreatedNotification { ProductId = productId };
        await _mediator.Publish(notification);
    }
}

Key Methods 📝

Vali-Mediator provides two primary methods through IValiMediator:

Send 🏗️

Sends a request to its registered handler, optionally processing it through a pipeline of behaviors:

var command = new CreateProductCommand { Name = "Laptop", Price = 999.99m };
int productId = await mediator.Send(command);
Publish 🔄

Publishes a notification to all registered handlers for asynchronous processing:

var notification = new ProductCreatedNotification { ProductId = 42 };
await mediator.Publish(notification);

Building Complex Pipelines 🧩

Vali-Mediator supports pipeline behaviors to add cross-cutting concerns like validation or logging. Here’s an example with a validation behavior:

Example: Validation Behavior
using Vali_Mediator.Core.General.Behavior;

public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
    public async Task<TResponse> Handle(TRequest request, Func<Task<TResponse>> next, CancellationToken cancellationToken)
    {
        // Add validation logic here (e.g., throw if invalid)
        Console.WriteLine("Validating request...");
        return await next();
    }
}

// Register in configuration
services.AddValiMediator(config =>
{
    config.RegisterServicesFromAssembly(typeof(Program).Assembly);
    config.AddBehavior(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
});

Comparison: Without vs. With Vali-Mediator ⚖️

Without Vali-Mediator (Manual Handling)

Manually resolving and calling handlers is verbose and tightly coupled:

var handler = serviceProvider.GetService<CreateProductCommandHandler>();
int productId = await handler.Handle(new CreateProductCommand { Name = "Laptop", Price = 999.99m }, CancellationToken.None);
Without Vali-Mediator (Manual Handling)

Vali-Mediator decouples the process with a clean, unified API:

int productId = await mediator.Send(new CreateProductCommand { Name = "Laptop", Price = 999.99m });

Features and Enhancements 🌟

Recent Updates

  • Multi-targeting support for .NET 7, 8, and 9.
  • Robust pipeline behavior system for extensibility.

Planned Features

  • Support for request pre-processing and post-processing hooks.
  • Enhanced debugging tools for pipeline execution.

Follow the project on GitHub for updates on new features and improvements!

Donations 💖

If you find Vali-Mediator useful and would like to support its development, consider making a donation:

Your contributions help keep this project alive and improve its development! 🚀

License 📜

This project is licensed under the Apache License 2.0.

Contributions 🤝

Feel free to open issues and submit pull requests to improve this library!

Product Compatible and additional computed target framework versions.
.NET net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (6)

Showing the top 5 NuGet packages that depend on Vali-Mediator:

Package Downloads
Vali-Mediator.Resilience

Zero-dependency resilience library for .NET 7/8/9/10. Provides Retry (with jitter/backoff), Circuit Breaker (sliding-window state machine), Timeout (optimistic + pessimistic), Fallback, Bulkhead, Rate Limiter (partitioned per-user/IP), Hedge, and Chaos policies via a fluent builder API. Attach policies to Vali-Mediator requests via IResiliencePolicyProvider<T> (no class needed), with global fallback policy support. No Polly or other external dependencies required.

Vali-Validation.ValiMediator

Vali-Mediator integration for Vali-Validation. Targets net7.0/net8.0/net9.0/net10.0. Adds a ValidationBehavior<TRequest, TResponse> that validates IRequest objects before they reach their handler. When TResponse is Result<T>, validation failures are returned as Result.Fail(errors, ErrorType.Validation) — no exceptions needed. For other response types, throws ValidationException. Package name: Vali-Validation.ValiMediator. Requires Vali-Mediator.

Vali-Mediator.Observability

Zero-dependency observability library for Vali-Mediator (.NET 7/8/9/10). Provides OpenTelemetry-compatible ActivitySource tracing, pluggable metrics via IMetricsCollector, and structured request lifecycle observers via IRequestObserver. Includes pipeline behaviours for IRequest and IDispatch (INotification / IFireAndForget), console implementations for quick diagnostics, and a fluent DI registration API. No OpenTelemetry SDK or other external dependencies required.

Vali-Mediator.AspNetCore

ASP.NET Core integration for Vali-Mediator. Maps Result<T> and Result to HTTP responses: Ok→200, Validation→400, NotFound→404, Conflict→409, Unauthorized→401, Forbidden→403, Failure→500. Provides ToActionResult() for MVC controllers and ToHttpResult() for Minimal API.

Vali-Mediator.Caching

Caching integration library for Vali-Mediator (.NET 7/8/9/10). Provides a pluggable ICacheStore abstraction, an in-memory implementation with expiry and group-based invalidation, and two pipeline behaviors: CachingBehavior (read-through / write-through) and CacheInvalidationBehavior. Zero external dependencies beyond Microsoft.Extensions.DependencyInjection.Abstractions and Vali-Mediator.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
3.0.0 231 10/1/2026
2.0.1 345 3/18/2026
2.0.0 546 3/16/2026
1.2.0 236 4/29/2025
1.1.0 266 4/7/2025
1.0.0 278 4/3/2025

Initial release of Vali-Mediator (v1.0.0). Supports .NET 7, 8, and 9 with CQRS, pipeline behaviors, and notification handling.