02 Core Concepts - vagnerjsmello/NexMediator GitHub Wiki
NexMediator is designed to support clean CQRS architecture with strongly-typed components.
Here are the main interfaces you'll use:
Interface | Description |
---|---|
INexRequest<TResponse> |
Base for all requests (generic) |
INexCommand<TResponse> |
Commands that change application state |
INexQuery<TResponse> |
Queries that read data (read-only) |
INexStreamRequest<T> |
Requests that stream async results (IAsyncEnumerable<T> ) |
public record CreateUserCommand(string Name, string Email) : INexCommand<UserDto>;
public class CreateUserHandler : INexRequestHandler<CreateUserCommand, UserDto>
{
public Task<UserDto> Handle(CreateUserCommand request, CancellationToken ct)
{
var user = new UserDto(Guid.NewGuid(), request.Name, request.Email);
return Task.FromResult(user);
}
}
// Usage
var result = await nexMediator.Send(new CreateUserCommand("Jane", "[email protected]"));
public record GetUserQuery(Guid Id) : INexQuery<UserDto>;
public class GetUserHandler : INexRequestHandler<GetUserQuery, UserDto>
{
public Task<UserDto> Handle(GetUserQuery query, CancellationToken ct)
{
return Task.FromResult(new UserDto(query.Id, "Jane Doe", "[email protected]"));
}
}
// Usage
var result = await nexMediator.Send(new GetUserQuery(Guid.Parse("...")));
public record SendEmailToUserNotification(string Email, string Subject, string Message) : INexNotification;
public class EmailSender : INexNotificationHandler<SendEmailToUserNotification>
{
public Task Handle(SendEmailToUserNotification notification, CancellationToken ct)
{
Console.WriteLine($"Sending email to {notification.Email} with subject {notification.Subject}");
return Task.CompletedTask;
}
}
// Usage
await nexMediator.Publish(new SendEmailToUserNotification("[email protected]", "Welcome", "Thanks for joining!"));
public record StreamUsersRequest() : INexStreamRequest<UserDto>;
public class StreamUsersHandler : INexStreamRequestHandler<StreamUsersRequest, UserDto>
{
public async IAsyncEnumerable<UserDto> Handle(StreamUsersRequest request, [EnumeratorCancellation] CancellationToken ct)
{
var users = new[]
{
new UserDto(Guid.NewGuid(), "Jane", "[email protected]"),
new UserDto(Guid.NewGuid(), "John", "[email protected]")
};
foreach (var user in users)
{
yield return user;
await Task.Delay(100, ct); // simulate stream delay
}
}
}
// Usage
await foreach (var user in nexMediator.Stream(new StreamUsersRequest(), cancellationToken))
{
Console.WriteLine(user.Name);
}
โ ๏ธ Note:Result<T>
is not part of NexMediator.
It is a custom pattern used in theAuctionBoardGame
example to standardize handler responses.
This pattern helps return:
- Success data
- HTTP status codes
- Error messages
return Result<UserDto>.Success(data);
return Result<UserDto>.BadRequest("Email is invalid");
return Result<UserDto>.NotFound("User not found");
It simplifies error handling and makes it easier to return consistent API responses.
Next: Examples