Lite.Validation.Rules.Inline 0.3.0-alpha

This is a prerelease version of Lite.Validation.Rules.Inline.
dotnet add package Lite.Validation.Rules.Inline --version 0.3.0-alpha
                    
NuGet\Install-Package Lite.Validation.Rules.Inline -Version 0.3.0-alpha
                    
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="Lite.Validation.Rules.Inline" Version="0.3.0-alpha" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Lite.Validation.Rules.Inline" Version="0.3.0-alpha" />
                    
Directory.Packages.props
<PackageReference Include="Lite.Validation.Rules.Inline" />
                    
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 Lite.Validation.Rules.Inline --version 0.3.0-alpha
                    
#r "nuget: Lite.Validation.Rules.Inline, 0.3.0-alpha"
                    
#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 Lite.Validation.Rules.Inline@0.3.0-alpha
                    
#: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=Lite.Validation.Rules.Inline&version=0.3.0-alpha&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Lite.Validation.Rules.Inline&version=0.3.0-alpha&prerelease
                    
Install as a Cake Tool

Lite.Validation

Библиотека валидации для .NET, заточенная под производительность и минимальное давление на GC. Fluent API, опциональный source generator, интеграции с ASP.NET Core (MVC, FastEndpoints) и DI.

NuGet: Lite.Validation
Бенчмарки (статья с цифрами): BENCHMARKS.md


Зачем это нужно

Валидация в веб-API вызывается на каждый запрос. В высоконагруженных сервисах это hot path: лишние наносекунды и аллокации складываются в миллисекунды и в постоянную нагрузку на сборщик мусора. Классические решения вроде FluentValidation или DataAnnotations удобны, но на каждый вызов тянут за собой рефлексию, скомпилированные делегаты, аллокации под результат и коллекции ошибок — в десятки раз больше времени и памяти, чем минимально необходимо.

Lite.Validation решает эту задачу иначе:

  • Source generator генерирует код валидации на этапе компиляции. Никакой рефлексии и Expression.Compile в рантайме — только прямой код, который JIT хорошо инлайнит.
  • Нулевые аллокации на успешной валидации: результат — структура, список ошибок создаётся только при наличии ошибок.
  • Тот же привычный fluent-подход — правила описываются в коде через RuleFor, цепочки правил, условия, вложенные валидаторы. Можно начать с runtime-варианта (LiteValidator + билдер) и позже перейти на source-generated без смены API.

Итог: в бенчмарках при тех же правилах мы обходим FluentValidation по времени в десятки раз и многократно снижаем аллокации и число Gen0-сборок на 10 000 запросов. Подробные цифры, таблицы и комментарии — в BENCHMARKS.md.


Пакеты

Пакет Описание
Lite.Validation Ядро: IValidator<T>, FluentValidator<T>, LiteValidator<T>, встроенные правила.
Lite.Validation.SourceGenerator Roslyn source generator: генерация Validate()/ValidateAsync() из FluentValidator<T> при компиляции.
Lite.Validation.Rules.Inline Дополнительные inline-правила (подключается ядром).
Lite.Validation.Integration.DependencyInjection AddLiteValidatorsFromAssembly() и регистрация в IServiceCollection.
Lite.Validation.Integration.AspNetCore.Mvc Интеграция с ASP.NET Core MVC.
Lite.Validation.Integration.AspNetCore.FastEndpoints Интеграция с FastEndpoints.

Быстрый старт

Вариант с ручной конфигурацией (LiteValidator)

Подходит, когда валидатор создаётся вручную или через DI с передачей билдера. Правила задаются в конструкторе.

public partial class CreateOrderValidator : LiteValidator<CreateOrderRequest>
{
    public CreateOrderValidator(ValidationBuilder<CreateOrderRequest> b) : base(b)
    {
        b.RuleFor(x => x.ProductName)
            .NotNull().WithDetails("Product name is required")
            .NotEmpty().WithDetails("Product name must not be empty");
        b.RuleFor(x => x.Quantity)
            .GreaterThan(0).WithDetails("Quantity must be positive");
    }
}

Вариант с source generator (FluentValidator)

Подключи пакет Lite.Validation.SourceGenerator. Правила описываются в статическом Configure; генератор создаёт реализацию валидатора в compile time — без рефлексии и лишних аллокаций.

public partial class OrderFluentValidator : FluentValidator<CreateOrderRequest>
{
    static void Configure(ValidationBuilder<CreateOrderRequest> b)
    {
        b.RuleFor(x => x.ProductName).NotNull().NotEmpty();
        b.RuleFor(x => x.Quantity).GreaterThan(0);
    }
}

Регистрация в DI

services.AddLiteValidatorsFromAssemblyOf<OrderFluentValidator>(ServiceLifetime.Singleton);

Сборка и тесты

dotnet build Lite.Validation.sln
dotnet test Lite.Validation.sln --no-build

Бенчмарки

Подробная статья с замерами против FluentValidation и DataAnnotations, разбором по одному запросу и по 10 000 запросов (время, аллокации, оценка Gen0): BENCHMARKS.md.

Запуск бенчмарков локально:

dotnet run -c Release --project benchmarks/Lite.Validation.Benchmarks -- --filter "*SimpleValidation*"
dotnet run -c Release --project benchmarks/Lite.Validation.Benchmarks -- --filter "*HighVolume*"

Отчёты (Markdown/HTML) сохраняются в BenchmarkDotNet.Artifacts/results/.


Разработка: окружение и хуки

Установка (mise, Python venv, pre-commit, dotnet tools):

  • Windows (PowerShell): .\install.ps1
  • Linux/macOS: ./install.sh (при необходимости: chmod +x install.sh)

При коммите запускаются форматтер (CSharpier) и сборка; при пуше — сборка и тесты.

Проверка хуков:

ls .git/hooks/pre-commit .git/hooks/pre-push

Ручной прогон:

pre-commit run --all-files
pre-commit run --hook-stage push --all-files

Если хуки не срабатывают: из корня выполни pre-commit install и pre-commit install --hook-type pre-push.

В .vscode/ — рекомендуемые расширения и настройки (CSharpier, format on save).

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 was computed.  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.
  • .NETStandard 2.0

    • No dependencies.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Lite.Validation.Rules.Inline:

Package Downloads
Lite.Validation

Lightweight validation for .NET: fluent API, sync/async rules, optional source generator for zero-overhead validators. No reflection, no Expression.Compile in generated path.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.3.0-alpha 100 3/16/2026