MVFC.Mediator 1.0.1

There is a newer version of this package available.
See the version list below for details.
dotnet add package MVFC.Mediator --version 1.0.1
                    
NuGet\Install-Package MVFC.Mediator -Version 1.0.1
                    
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="MVFC.Mediator" Version="1.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="MVFC.Mediator" Version="1.0.1" />
                    
Directory.Packages.props
<PackageReference Include="MVFC.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 MVFC.Mediator --version 1.0.1
                    
#r "nuget: MVFC.Mediator, 1.0.1"
                    
#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 MVFC.Mediator@1.0.1
                    
#: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=MVFC.Mediator&version=1.0.1
                    
Install as a Cake Addin
#tool nuget:?package=MVFC.Mediator&version=1.0.1
                    
Install as a Cake Tool

MVFC.Mediator

MVFC.Mediator é uma biblioteca .NET que implementa o padrão Mediator, promovendo a comunicação desacoplada entre componentes de uma aplicação. O Mediator centraliza o envio de comandos e eventos, facilitando a manutenção e evolução do código.

Visão Geral

O padrão Mediator permite que objetos se comuniquem sem depender diretamente uns dos outros, reduzindo o acoplamento e tornando o sistema mais modular. MVFC.Mediator abstrai essa comunicação por meio de interfaces e handlers.

Principais Componentes

  • ICommand: Interface base para comandos, representando uma solicitação de ação.
  • ICommandHandler: Interface para handlers responsáveis por processar comandos específicos.
  • IMediator: Interface que define o contrato para envio de comandos e publicação de eventos.
  • Mediator: Implementação concreta do IMediator, responsável por resolver e invocar os handlers.

Recursos

  • Suporte à injeção de dependências para handlers
  • Facilidade de integração em projetos .NET (Console, WebAPI, etc.)
  • Extensível para eventos, notificações e queries
  • Benchmarks e testes automatizados

Instalação

Adicione o projeto como referência em sua solução ou instale via NuGet (se disponível):

dotnet add package MVFC.Mediator

Exemplo de Uso

Adicionar injeção de independência

builder.Services.AddMediator();
builder.Services.AddValidatorsFromAssemblyContaining<Program>();

Definir o Retorno

public sealed record class CreateUserResponse(Guid UserId, string Name, string Email, DateTime CreatedAt);

Defina um comando:

public sealed record class CreateUserCommand(string Name, string Email, int Age) : 
    ICommand<CreateUserResponse>;

Implemente o handler:

public sealed class CreateUserCommandHandler(ILogger<CreateUserCommandHandler> logger) : 
ICommandHandler<CreateUserCommand, CreateUserResponse>
{
    private readonly ILogger<CreateUserCommandHandler> _logger = logger;

    public async ValueTask<CreateUserResponse> Handle(CreateUserCommand command, CancellationToken cancellationToken = default)
    {
        _logger.LogInformation("Criando usuário: {Name}", command.Name);

        var userId = Guid.NewGuid();
        var createdAt = DateTime.UtcNow;

        await Task.Delay(TimeSpan.FromMilliseconds(1), cancellationToken);

        return new CreateUserResponse(userId, command.Name, command.Email, createdAt);
    }
}

Envie o comando via Mediator:

endpoints.MapPost("/api/users", async (IMediator mediator, CreateUserCommand command, CancellationToken ct) =>
{
    var response = await mediator.Send<CreateUserCommand, CreateUserResponse>(command, ct);
    return Results.Created($"/api/users/{response.UserId}", response);
})
.Produces<CreateUserResponse>(StatusCodes.Status201Created)
.Produces<ProblemDetails>(StatusCodes.Status422UnprocessableEntity);

Estrutura do Projeto

Testes e Benchmarks

Os testes e benchmarks estão no Report, garantindo performance e confiabilidade.


BenchmarkDotNet v0.15.4, Windows 11 (10.0.26200.6901)
12th Gen Intel Core i5-12500H 2.50GHz, 1 CPU, 16 logical and 12 physical cores
.NET SDK 9.0.302
  [Host]     : .NET 9.0.7 (9.0.7, 9.0.725.31616), X64 RyuJIT x86-64-v3
  Job-NTRUNJ : .NET 9.0.7 (9.0.7, 9.0.725.31616), X64 RyuJIT x86-64-v3

IterationCount=5  WarmupCount=3  

Method Mean Error StdDev Gen0 Allocated
'Simula request HTTP individual' 1.364 μs 0.2325 μs 0.0604 μs 0.4272 3.97 KB
'Simula múltiplos requests em paralelo' 13.688 μs 2.2724 μs 0.3517 μs 4.3335 40.15 KB

Licença

Este projeto está sob a licença MIT.

Product Compatible and additional computed target framework versions.
.NET 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

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
3.3.0 130 5/22/2026
3.2.0 179 4/5/2026
3.1.0 104 4/1/2026
2.0.2 99 3/21/2026
2.0.1 93 3/20/2026
2.0.0 91 3/20/2026
1.1.0 311 11/16/2025
1.0.1 207 10/27/2025
1.0.0 198 10/27/2025