ExpressValidator.Extensions.DependencyInjection 0.4.0

dotnet add package ExpressValidator.Extensions.DependencyInjection --version 0.4.0
                    
NuGet\Install-Package ExpressValidator.Extensions.DependencyInjection -Version 0.4.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="ExpressValidator.Extensions.DependencyInjection" Version="0.4.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ExpressValidator.Extensions.DependencyInjection" Version="0.4.0" />
                    
Directory.Packages.props
<PackageReference Include="ExpressValidator.Extensions.DependencyInjection" />
                    
Project file
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 ExpressValidator.Extensions.DependencyInjection --version 0.4.0
                    
#r "nuget: ExpressValidator.Extensions.DependencyInjection, 0.4.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 ExpressValidator.Extensions.DependencyInjection@0.4.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=ExpressValidator.Extensions.DependencyInjection&version=0.4.0
                    
Install as a Cake Addin
#tool nuget:?package=ExpressValidator.Extensions.DependencyInjection&version=0.4.0
                    
Install as a Cake Tool

The ExpressValidator.Extensions.DependencyInjection package extends ExpressValidator to provide integration with Microsoft Dependency Injection.

Key Features

  • Automatic DI Registration: Configures and registers IExpressValidator<T> with Microsoft's Dependency Injection container.
  • Class-Based Configuration: Define validation rules via dedicated configurator classes inheriting from ValidatorConfigurator<T>, providing an alternative to inline configuration.
  • Dynamic Parameter Updates: Registers IExpressValidatorBuilder<T, TOptions> to automatically update validation parameters when configuration options change.
  • Automatic Reload Capability: Automatically reload validation rules when configuration changes using IExpressValidatorWithReload<T>.

Quick Start

Register an IExpressValidator<T> implementation in the dependency injection (DI) container using the AddExpressValidator method, then inject and use it in a consuming service:

using ExpressValidator;
using ExpressValidator.Extensions.DependencyInjection;
using FluentValidation;

var builder = WebApplication.CreateBuilder(args);

// Registers the validator for ObjToValidate with specified validation rules.
builder.Services.AddExpressValidator<ObjToValidate>(b => 
        b.AddProperty(o => o.I)
	    .WithValidation(o => o.GreaterThan(5)
	    .WithMessage("Must be greater than 5!")));

// Registers the service that will use the validator.
builder.Services.AddTransient<IGuessTheNumberService, GuessTheNumberService>();

var app = builder.Build();

app.MapGet("/guess", (IGuessTheNumberService service) =>
{
	var (Result, Message) = service.Guess();
	if (!Result)
	{
		return Results.BadRequest(Message);
	}
	// Additional logic here...
});

await app.RunAsync();

// ... (Other code omitted for brevity)

// Service interface definition.
public interface IGuessTheNumberService
{
	(bool Result, string Message) Guess();
}

// Service implementation that uses the validator.
public class GuessTheNumberService : IGuessTheNumberService
{
	private readonly IExpressValidator<ObjToValidate> _expressValidator;

	public GuessTheNumberService(IExpressValidator<ObjToValidate> expressValidator)
	{
		_expressValidator = expressValidator;
	}

	public (bool Result, string Message) Guess()
	{
		...
		var vr = _expressValidator.Validate(objToValidate);
		if (!vr.IsValid)
		{
			...
		}
		// ... (Additional logic)
	}
}
// ... (Other code omitted for brevity)

Quick Start: Using a ValidatorConfigurator<T> (Alternative Approach)

As an alternative to inline configuration, you can define validation rules by creating a dedicated configurator class that inherits from ValidatorConfigurator<T>, where T is the type being validated:

/// <summary>
/// Configures validation rules for ObjToValidate.
/// </summary>
public class GuessValidatorConfigurator : ValidatorConfigurator<ObjToValidate>
{
	/// <summary>
    /// Configures the validator builder with rules.
    /// </summary>
	public override void Configure(ExpressValidatorBuilder<ObjToValidate> expressValidatorBuilder)
		=> expressValidatorBuilder
			.AddProperty(o => o.I)
			.WithValidation((o) => o.GreaterThan(5));
}

Then use AddExpressValidation method to register the configurator in DI:

var builder = WebApplication.CreateBuilder(args);

// Scans the assembly and registers validators from configurators.
builder.Services.AddExpressValidation(Assembly.GetExecutingAssembly());

// Registers the service that will use the validator.
builder.Services.AddTransient<IGuessTheNumberService, GuessTheNumberService>();

// ... (Application build and run code omitted; same as in Quick Start)

// The GuessTheNumberService implementation remains the same as in the Quick Start example.
// ... (Other code omitted for brevity)

Validation with Options

In this approach, register an IExpressValidatorBuilder<T, TOptions> implementation (instead of IExpressValidator<T>) in the DI container by calling the AddExpressValidatorBuilder method.

var builder = WebApplication.CreateBuilder(args);

// Registers the validator builder with options-dependent rules.
builder.Services.AddExpressValidatorBuilder<ObjToValidate, ValidationParametersOptions>(b =>
	b.AddProperty(o => o.I)
	.WithValidation((to, rbo) => rbo.GreaterThan(to.IGreaterThanValue)
	.WithMessage($"Must be greater than {to.IGreaterThanValue}!")));

builder.Services.AddTransient<IAdvancedNumberGuessingService, AdvancedNumberGuessingService>();

// Configures options from the application settings.
builder.Services.Configure<ValidationParametersOptions>(builder.Configuration.GetSection("ValidationParameters"));

var app = builder.Build();

app.MapGet("/complexguess", (IAdvancedNumberGuessingService service) =>
{
	var (Result, Message) = service.ComplexGuess();
	if (!Result)
	{
		return Results.BadRequest(Message);
	}
	// Additional logic here...
});

app.Run();

// Service interface definition:
public interface IAdvancedNumberGuessingService
{
	(bool Result, string Message) ComplexGuess();
}

// Service implementation that builds and uses the validator with options.
public class AdvancedNumberGuessingService : IAdvancedNumberGuessingService
{
	private readonly ValidationParametersOptions _validateOptions;
	private readonly IExpressValidatorBuilder<ObjToValidate, ValidationParametersOptions> _expressValidatorBuilder;

	public AdvancedNumberGuessingService(IExpressValidatorBuilder<ObjToValidate, ValidationParametersOptions> expressValidatorBuilder,
		IOptions<ValidationParametersOptions> validateOptions)
	{
		_validateOptions = validateOptions.Value;
		_expressValidatorBuilder = expressValidatorBuilder;
	}

	//Updates options, rebuilds the validator, and validates.
	public (bool Result, string Message) ComplexGuess()
	{
		...
		ChangeValidateOptions();

		var vr = _expressValidatorBuilder.Build(_validateOptions).Validate(objToValidate);
		if (!vr.IsValid)
		{
			// ... (Handle invalid case)
		}
		// ... (Additional logic)
	}

	private void ChangeValidateOptions()
	{
		// ... (Option update logic omitted)
	}
}

In the appsettings.json

{
// ... (Other settings omitted)
"ValidationParameters": {
  "IGreaterThanValue": 5
 }
}

Validation with Automatic Reload on Configuration Changes

To validate options when configuration changes - without restarting the application - use the AddExpressValidatorWithReload method:

var builder = WebApplication.CreateBuilder(args);

// Registers a reloadable validator that updates on configuration changes.
builder.Services.AddExpressValidatorWithReload<ObjToValidate, ValidationParametersOptions>(b =>
	b.AddProperty(o => o.I)
	.WithValidation((to, rbo) => rbo.GreaterThan(to.IGreaterThanValue)
	.WithMessage($"Must be greater than {to.IGreaterThanValue}!")),
	"ValidationParameters");

// Registers the reloadable service.
builder.Services.AddTransient<IReloadableNumberGuessingService, ReloadableNumberGuessingService>();

// Configures options from the application settings.
builder.Services.Configure<ValidationParametersOptions>(builder.Configuration.GetSection("ValidationParameters"));

var app = builder.Build();

app.MapGet("/guesswithreload", (IReloadableNumberGuessingService service) =>
{
	var (Result, Message) = service.GuessWithReload();
	if (!Result)
	{
		return Results.BadRequest(Message);
	}
	// Additional logic here...
});

// Service interface definition.
public interface IReloadableNumberGuessingService
{
	(bool Result, string Message) GuessWithReload();
}

// Service implementation that uses the reloadable validator.
public class ReloadableNumberGuessingService : IReloadableNumberGuessingService
{
	private readonly IExpressValidatorWithReload<ObjToValidate> _expressValidatorWithReload;

	public ReloadableNumberGuessingService(IExpressValidatorWithReload<ObjToValidate> expressValidatorWithReload)
	{
		_expressValidatorWithReload = expressValidatorWithReload;
	}

	public (bool Result, string Message) GuessWithReload()
	{
		...
		var vr = _expressValidatorWithReload.Validate(objToValidate);
		if (!vr.IsValid)
		{
			...
		}
	}
}

Samples

See samples folder for concrete example.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  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.  net9.0 was computed.  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. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos 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
0.4.0 82 1/13/2026
0.3.12 134 10/10/2025
0.3.9 448 7/25/2025
0.3.7 297 6/13/2025
0.3.5 224 4/9/2025
0.3.2 149 2/25/2025
0.3.0 141 1/17/2025
0.2.1 165 12/11/2024
0.2.0 148 11/15/2024
0.0.1 167 10/9/2024