PlumbR 1.0.1

dotnet add package PlumbR --version 1.0.1                
NuGet\Install-Package PlumbR -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="PlumbR" Version="1.0.1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add PlumbR --version 1.0.1                
#r "nuget: PlumbR, 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.
// Install PlumbR as a Cake Addin
#addin nuget:?package=PlumbR&version=1.0.1

// Install PlumbR as a Cake Tool
#tool nuget:?package=PlumbR&version=1.0.1                

PlumbR

PlumbR is a minimal api microservices framework that leverages MediatR to provide handlers for ASP.NET Core Minimal APIs, using FluentValidation to validate the MediatR requests, along with OneOf discriminated unions to allow the pipelines to return success values or problem details from the handlers.

Installation

Install the package via NuGet:

dotnet add package PlumbR

Configuration

To set up PlumbR, first configure MediatR and FluentValidation as usual, then add cfg.AddValidationBehaviorForAssemblyContaining<>() to AddMediatR to wire up the behavior that runs FluentValidation validators before the pipeline handlers.

builder.Services.AddMediatR(cfg =>
{
  cfg.RegisterServicesFromAssemblyContaining<Program>();
  cfg.AddValidationBehaviorForAssemblyContaining<Program>();
});
services.AddValidatorsFromAssemblyContaining<Program>();

Usage

Endpoints

  • Pass Pipeline.HandleBody<TRequest, TResult> as the delegate to the endpoint mapping to bind the request using [FromBody].
  • Pass Pipeline.HandleParameters<TRequest, TResult> as the delegate to bind the request using [AsParameters]. This will allow binding each property on the request model from different sources including [FromRoute], [FromQuery], [FromBody], etc.
app.MapGet("/parameters/{Id:int}", Pipeline.HandleParameters<ParameterRequest, ParametersResult>);
app.MapPost("/body", Pipeline.HandleBody<BodyRequest, BodyResult>);

Handler, Request, and Result

Request and Handler classes use IPipelineRequest<TResult> and IPipelineHandler<TRequest, TResult> interfaces to match up with the validators. the return value PipelineResult<TResult> can be one of TResult or ProblemDetails.

public class BodyRequest : IPipelineRequest<BodyResult>
{
  public required int Id { get; init; }
  public required string Name { get; set; }
}

public class BodyResult
{
  public required string Message { get; init; }
}

public class BodyHandler : IPipelineHandler<BodyRequest, BodyResult>
{
  private readonly TestService service;

  public BodyHandler(TestService service)
  {
    this.service = service;
  }

  public async Task<PipelineResult<BodyResult>> Handle(BodyRequest request, CancellationToken cancellationToken)
  {
    try
    {
      await service.SaveId(request.Id, cancellationToken);
    }
    catch (SaveFailedException e)
    {
      return new ProblemDetails
      {
        Status = StatusCodes.Status422UnprocessableEntity,
        Title = e.Message
      };
    }

    return new BodyResult
    {
      Message = $"Hello, {request.Name}! Your ID {request.Id} was saved."
    };
  }
}

Validation

Write validators as you normally would on the request types.

public class BodyRequestValidator : AbstractValidator<BodyRequest>
{
    public BodyRequestValidator()
    {
        RuleFor(x => x.Id).GreaterThan(0);
    }
}

Pipeline Behaviors

Implement IPipelineBehavior<TRequest, PipelineResult<TResponse>> for preprocessing and postprocessing of requests and responses:

public class LoggerBehavior<TRequest, TResult> : IPipelineBehavior<TRequest, PipelineResult<TResult>>
  where TRequest : notnull
{
  private readonly ILogger<LoggerBehavior<TRequest, TResult>> logger;

  public LoggerBehavior(ILogger<LoggerBehavior<TRequest, TResult>> logger)
  {
    this.logger = logger;
  }

  public async Task<PipelineResult<TResult>> Handle(TRequest request, RequestHandlerDelegate<PipelineResult<TResult>> next, CancellationToken cancellationToken)
  {
    logger.LogInformation("Handling request: {request}", JsonSerializer.Serialize(request));
    var result = await next();
    logger.LogInformation("Handled request with result: {response}", JsonSerializer.Serialize(result));
    return result;
  }
}

To automatically register generic behaviors for all request and response types, you can use AddPipelineBehaviorForAssemblyContaining<T>(). Normally MediatR's AddOpenBehavior would be used here, but it has trouble wiring up open behaviors when the result is another generic type like PipelineRequest<TResponse>.

services.AddMediatR(cfg =>
{
  // ...
  cfg.AddPipelineBehaviorForAssemblyContaining<Program>(typeof(LoggerBehavior<,>));
});

API Sample

See the TestApi project for a full sample API.

License

This project is licensed under the Apache License Version 2.0 - see the LICENSE file for details.

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.1 78 7/23/2024
1.0.0 910 4/22/2024
1.0.0-beta002 103 4/18/2024
1.0.0-beta001 100 4/7/2024