Biss.Mediator.Extensions.AspNetCore
1.0.0
dotnet add package Biss.Mediator.Extensions.AspNetCore --version 1.0.0
NuGet\Install-Package Biss.Mediator.Extensions.AspNetCore -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="Biss.Mediator.Extensions.AspNetCore" Version="1.0.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Biss.Mediator.Extensions.AspNetCore" Version="1.0.0" />
<PackageReference Include="Biss.Mediator.Extensions.AspNetCore" />
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 Biss.Mediator.Extensions.AspNetCore --version 1.0.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: Biss.Mediator.Extensions.AspNetCore, 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 Biss.Mediator.Extensions.AspNetCore@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=Biss.Mediator.Extensions.AspNetCore&version=1.0.0
#tool nuget:?package=Biss.Mediator.Extensions.AspNetCore&version=1.0.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
Biss.Mediator.Extensions.AspNetCore
Extensões do Biss.Mediator para integração com ASP.NET Core.
📦 Instalação
dotnet add package Biss.Mediator.Extensions.AspNetCore
🚀 Uso Rápido
1. Registrar o Mediator no Startup
using Biss.Mediator.Extensions.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
// Adicionar Mediator com suporte a ASP.NET Core
builder.Services.AddMediatorWithAspNetCore(typeof(Program).Assembly);
// Ou especificar assemblies manualmente
builder.Services.AddMediatorWithAspNetCore(
typeof(Program).Assembly,
typeof(MyCommand).Assembly
);
2. Criar um Controller Baseado em Mediator
using Biss.Mediator.Abstractions;
using Biss.Mediator.Extensions.AspNetCore;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class UsersController : MediatorControllerBase
{
public UsersController(IMediator mediator) : base(mediator)
{
}
[HttpPost]
public async Task<ActionResult<UserId>> CreateUser(CreateUserCommand command)
{
// O método Send automaticamente mapeia Result<T> para ActionResult<T>
return await Send(command);
}
[HttpGet("{id}")]
public async Task<ActionResult<UserDto>> GetUser(Guid id)
{
var query = new GetUserQuery(id);
return await Send(query);
}
[HttpDelete("{id}")]
public async Task<ActionResult> DeleteUser(Guid id)
{
var command = new DeleteUserCommand(id);
return await Send(command);
}
[HttpPost("{id}/activate")]
public async Task<ActionResult> ActivateUser(Guid id)
{
var command = new ActivateUserCommand(id);
// Usar status code customizado
return await Send(command, System.Net.HttpStatusCode.Accepted);
}
}
3. Definir Commands e Queries
// Command
public record CreateUserCommand(string FirstName, string LastName, string Email)
: ICommand<UserId>;
// Query
public record GetUserQuery(Guid Id) : IQuery<UserDto>;
// Command sem retorno
public record DeleteUserCommand(Guid Id) : ICommand;
4. Criar Handlers
public class CreateUserHandler : ICommandHandler<CreateUserCommand, UserId>
{
public async Task<Result<UserId>> Handle(
CreateUserCommand request,
CancellationToken cancellationToken)
{
// Sua lógica aqui
var userId = new UserId(Guid.NewGuid());
return Result<UserId>.Success(userId);
}
}
📚 Recursos
MediatorControllerBase
A classe base MediatorControllerBase fornece métodos auxiliares para enviar requests e commands:
Send<TResponse>(IRequest<TResponse>)- Envia um request e retorna ActionResult<TResponse>Send(ICommand)- Envia um command sem retornoSend<TResponse>(ICommand<TResponse>)- Envia um command com retornoSend<TResponse>(IRequest<TResponse>, int statusCode)- Envia com status code customizadoPublish(INotification)- Publica uma notificação
Mapeamento Automático de Erros
O MediatorControllerBase mapeia automaticamente erros para códigos HTTP apropriados:
NotFoundError→ 404 Not FoundValidationError→ 400 Bad RequestUnauthorizedError→ 401 Unauthorized- Outros erros → 500 Internal Server Error
HttpContext Extensions
Você também pode acessar o Mediator diretamente do HttpContext:
public class MyMiddleware
{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var mediator = context.GetMediator();
// Usar o mediator aqui
await _next(context);
}
}
🔧 Configuração Avançada
Configurar MVC Options
builder.Services.ConfigureMediatorMvc(options =>
{
// Configurar opções do MVC relacionadas ao Mediator
});
📖 Exemplos Completos
Exemplo: CRUD Completo
[ApiController]
[Route("api/customers")]
public class CustomersController : MediatorControllerBase
{
public CustomersController(IMediator mediator) : base(mediator)
{
}
[HttpPost]
public async Task<ActionResult<CustomerId>> Create(CreateCustomerCommand command)
=> await Send(command, StatusCodes.Status201Created);
[HttpGet("{id}")]
public async Task<ActionResult<CustomerDto>> Get(Guid id)
=> await Send(new GetCustomerQuery(id));
[HttpPut("{id}")]
public async Task<ActionResult> Update(Guid id, UpdateCustomerCommand command)
=> await Send(command);
[HttpDelete("{id}")]
public async Task<ActionResult> Delete(Guid id)
=> await Send(new DeleteCustomerCommand(id));
[HttpGet]
public async Task<ActionResult<PagedResult<CustomerDto>>> List(
[FromQuery] GetCustomersQuery query)
=> await Send(query);
}
🎯 Benefícios
- ✅ Type Safety: Compile-time validation de requests e responses
- ✅ Clean Code: Controllers limpos e focados apenas em HTTP
- ✅ Error Handling: Mapeamento automático de erros para HTTP
- ✅ Testability: Fácil de testar com mocks do IMediator
- ✅ Performance: Source Generators eliminam reflection overhead
📄 Licença
Este projeto está licenciado sob a Licença MIT.
| Product | Versions 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.
-
net9.0
- Biss.Mediator.Abstractions (>= 1.0.0)
- Biss.Mediator.Extensions.DependencyInjection (>= 1.0.0)
- Microsoft.AspNetCore.Http.Abstractions (>= 2.2.0)
- Microsoft.AspNetCore.Mvc.Core (>= 2.2.5)
- Microsoft.Extensions.DependencyInjection (>= 9.0.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 9.0.0)
- Microsoft.Extensions.Hosting.Abstractions (>= 9.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 9.0.0)
- Microsoft.Extensions.Options (>= 9.0.0)
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 |
|---|---|---|
| 1.0.0 | 296 | 12/7/2025 |