Table of Contents

Class ServiceCollectionExtensions

Namespace
Trellis.Asp
Assembly
Trellis.Asp.dll

Extension methods for configuring automatic value object validation in ASP.NET Core.

public static class ServiceCollectionExtensions
Inheritance
ServiceCollectionExtensions
Inherited Members

Methods

AddScalarValueValidation(IMvcBuilder)

Adds automatic validation for scalar value types during model binding and JSON deserialization.

public static IMvcBuilder AddScalarValueValidation(this IMvcBuilder builder)

Parameters

builder IMvcBuilder

The IMvcBuilder.

Returns

IMvcBuilder

The IMvcBuilder for chaining.

Examples

Registration in Program.cs:

using Trellis;

var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddControllers()
    .AddScalarValueValidation();

var app = builder.Build();
app.MapControllers();
app.Run();

Usage in controllers with automatic validation:

public record RegisterUserDto
{
    public EmailAddress Email { get; init; } = null!;
    public FirstName FirstName { get; init; } = null!;
}

[ApiController]
[Route("api/users")]
public class UsersController : ControllerBase
{
    [HttpPost]
    public IActionResult Register(RegisterUserDto dto)
    {
        // If we reach here, dto is fully validated!
        // All scalar values passed validation

        var user = User.TryCreate(dto.Email, dto.FirstName);
        return user.ToActionResult(this);
    }
}

Remarks

This method configures ASP.NET Core to automatically validate scalar values that implement IScalarValue<TSelf, TPrimitive> during:

  • Model binding: Values from route, query, form, or headers
  • JSON deserialization: Values from request body (with error collection)

Unlike traditional validation that throws on first error, this approach:

  • Collects ALL validation errors during JSON deserialization
  • Uses property names (not JSON paths) in error messages
  • Returns comprehensive 400 Bad Request with all field errors
  • Integrates seamlessly with [ApiController] attribute

AddScalarValueValidation(IServiceCollection)

Adds automatic value object validation for both MVC Controllers and Minimal APIs. This is a convenience method that configures validation for all ASP.NET Core application types.

public static IServiceCollection AddScalarValueValidation(this IServiceCollection services)

Parameters

services IServiceCollection

The service collection.

Returns

IServiceCollection

The service collection for chaining.

Examples

Simple setup for mixed applications:

var builder = WebApplication.CreateBuilder(args);

// Unified setup - works for both MVC and Minimal APIs
builder.Services.AddControllers();
builder.Services.AddScalarValueValidation();

var app = builder.Build();

app.UseScalarValueValidation();
app.MapControllers();
app.MapPost("/api/users", (RegisterDto dto) => ...).WithScalarValueValidation();

app.Run();

For MVC-only applications, prefer the fluent API:

builder.Services
    .AddControllers()
    .AddScalarValueValidation(); // ← Better for MVC-only apps

Remarks

This method is equivalent to calling both:

Use this method when you have both controllers and Minimal API endpoints in your application, or when you're not sure which style you'll use. For applications using only one approach, prefer the specific methods for clarity.

Note: This method does NOT configure MVC-specific features like model binding or the validation filter. If you're using MVC controllers with the [ApiController] attribute, use AddControllers().AddScalarValueValidation() instead for full functionality.

AddScalarValueValidationForMinimalApi(IServiceCollection)

Configures HTTP JSON options to use property-aware value object validation for Minimal APIs.

public static IServiceCollection AddScalarValueValidationForMinimalApi(this IServiceCollection services)

Parameters

services IServiceCollection

The service collection.

Returns

IServiceCollection

The service collection for chaining.

Examples

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScalarValueValidationForMinimalApi();

var app = builder.Build();
app.UseScalarValueValidation();

app.MapPost("/users", (RegisterUserDto dto) => ...)
   .WithScalarValueValidation();

Remarks

This method configures Minimal API JSON serialization to automatically validate value objects that implement IScalarValue<TSelf, TPrimitive> during JSON deserialization.

For Minimal APIs, also use UseScalarValueValidation(IApplicationBuilder) middleware and WithScalarValueValidation(RouteHandlerBuilder) on your route handlers.

AddTrellisAsp(IServiceCollection)

Registers Trellis ASP.NET Core integration with default error-to-HTTP-status-code mappings.

public static IServiceCollection AddTrellisAsp(this IServiceCollection services)

Parameters

services IServiceCollection

The service collection.

Returns

IServiceCollection

The service collection for chaining.

Examples

builder.Services.AddTrellisAsp();

Remarks

This method uses the default error-to-status-code mappings. Most teams can use this zero-configuration overload. Call the overload accepting Action<T> to customize specific mappings.

AddTrellisAsp(IServiceCollection, Action<TrellisAspOptions>)

Registers Trellis ASP.NET Core integration with custom error-to-HTTP-status-code mappings.

public static IServiceCollection AddTrellisAsp(this IServiceCollection services, Action<TrellisAspOptions> configure)

Parameters

services IServiceCollection

The service collection.

configure Action<TrellisAspOptions>

An action to configure error-to-HTTP-status-code mappings.

Returns

IServiceCollection

The service collection for chaining.

Examples

builder.Services.AddTrellisAsp(options =>
{
    options.MapError<DomainError>(StatusCodes.Status400BadRequest);
});

Remarks

Default mappings are applied first. The configure action can override any mapping using MapError<TError>(int).

UseScalarValueValidation(IApplicationBuilder)

Adds middleware that creates a validation error collection scope for each request. This middleware must be registered in the pipeline to enable validation error collection.

public static IApplicationBuilder UseScalarValueValidation(this IApplicationBuilder app)

Parameters

app IApplicationBuilder

The application builder.

Returns

IApplicationBuilder

The application builder for chaining.

Examples

var app = builder.Build();

app.UseScalarValueValidation(); // ← Add this before routing
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

app.Run();

Remarks

This middleware creates a ValidationErrorsContext scope for each request, allowing ValidatingJsonConverter<TValue, TPrimitive> to collect validation errors during JSON deserialization.

Register this middleware early in the pipeline, before any middleware that deserializes JSON request bodies (such as routing or MVC).

WithScalarValueValidation(RouteHandlerBuilder)

Adds the value object validation endpoint filter to the route handler.

public static RouteHandlerBuilder WithScalarValueValidation(this RouteHandlerBuilder builder)

Parameters

builder RouteHandlerBuilder

The route handler builder.

Returns

RouteHandlerBuilder

The route handler builder for chaining.

Examples

app.MapPost("/users/register", (RegisterUserDto dto) =>
{
    // dto is already validated
    return Results.Ok(dto);
}).WithScalarValueValidation();

Remarks

This extension adds ScalarValueValidationEndpointFilter to check for validation errors collected during JSON deserialization.

Ensure UseScalarValueValidation(IApplicationBuilder) middleware is registered and AddScalarValueValidationForMinimalApi(IServiceCollection) is called for full functionality.