MediatorForge.Adapters 1.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package MediatorForge.Adapters --version 1.0.0                
NuGet\Install-Package MediatorForge.Adapters -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="MediatorForge.Adapters" Version="1.0.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add MediatorForge.Adapters --version 1.0.0                
#r "nuget: MediatorForge.Adapters, 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.
// Install MediatorForge.Adapters as a Cake Addin
#addin nuget:?package=MediatorForge.Adapters&version=1.0.0

// Install MediatorForge.Adapters as a Cake Tool
#tool nuget:?package=MediatorForge.Adapters&version=1.0.0                

MediatorForge.Adapters

Overview

The FluentValidatorAdapter<TRequest> is an adapter class that integrates FluentValidation validators with a custom validation system. This adapter allows you to use FluentValidation within your validation pipeline seamlessly.

Installation

To install the FluentValidatorAdapter, run the following command in the NuGet Package Manager Console:

dotnet add package MediatorForge.Adapters

Usage

Adding to Service Collection

Add and configure the FluentValidatorAdapter to your IServiceCollection in your Startup.cs or Program.cs file:

public void ConfigureServices(IServiceCollection services)
{
    // Add MediatR
    services.AddMediatR(typeof(Startup));

    // Add FluentValidation
    services.AddTransient<IValidator<CreateItemCommand>, CreateItemCommandValidator>();

    // Add FluentValidatorAdapter
    services.AddMediatorForgeFluentValidatorAdapter();

    // Other service registrations
}

Defining Your Request and Command

Define your request and create a corresponding command:

public class CreateItemCommand : IRequest<Guid>
{
    public string Name { get; set; }
    public string Description { get; set; }
}

Creating a Validator

Create a validator for your request using FluentValidation:

using FluentValidation;

public class CreateItemCommandValidator : AbstractValidator<CreateItemCommand>
{
    public CreateItemCommandValidator()
    {
        RuleFor(x => x.Name).NotEmpty().WithMessage("Name is required.");
        RuleFor(x => x.Description).NotEmpty().WithMessage("Description is required.");
    }
}

Implementing Command Handler

Create a handler for your command:

using MediatR;
using System;
using System.Threading;
using System.Threading.Tasks;

public class CreateItemCommandHandler : IRequestHandler<CreateItemCommand, Guid>
{
    public Task<Guid> Handle(CreateItemCommand request, CancellationToken cancellationToken)
    {
        // Business logic to handle the command
        var itemId = Guid.NewGuid();
        return Task.FromResult(itemId);
    }
}

Creating a Controller

Create a controller to handle the HTTP requests:

using MediatR;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;

[ApiController]
[Route("api/[controller]")]
public class ItemsController : ControllerBase
{
    private readonly IMediator _mediator;

    public ItemsController(IMediator mediator)
    {
        _mediator = mediator;
    }

    [HttpPost]
    public async Task<IActionResult> CreateItem([FromBody] CreateItemCommand command)
    {
        var itemId = await _mediator.Send(command);
        return Ok(itemId);
    }
}

Example Request and Response

Example Request
POST /api/items
{
    "name": "NewItem",
    "description": "Description of the new item"
}
Expected Response
{
    "itemId": "generated-item-id"
}

FluentValidatorAdapter<TRequest> Class

/// <summary>
/// Adapter class to integrate FluentValidation validators with the custom validation system.
/// </summary>
/// <typeparam name="TRequest">The type of the request to be validated.</typeparam>
public class FluentValidatorAdapter<TRequest>(FluentValidation.IValidator<TRequest> fluentValidator) : IValidator<TRequest>
    where TRequest : IRequest
{
    /// <inheritdoc/>
    /// <returns>A task that represents the asynchronous validation operation. The task result contains the <see cref="ValidationResult"/>.</returns>
    public async Task<ValidationResult> ValidateAsync(TRequest request, CancellationToken cancellationToken = default)
    {
        var validationResult = await fluentValidator.ValidateAsync(request);

        if (validationResult.IsValid)
        {
            return ValidationResult.Success;
        }

        var errors = validationResult.Errors.Select(e => new ValidationError(e.PropertyName, e.ErrorMessage, e.AttemptedValue));
        return ValidationResult.Failure(errors);
    }
}

Documentations

License

This project is licensed under the MIT License.


Product Compatible and additional computed target framework versions.
.NET 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. 
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
1.0.3 47 12/25/2024
1.0.2 47 12/25/2024
1.0.1 107 12/6/2024
1.0.0 115 11/30/2024