Motiv 9.1.0

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

<img src="https://raw.githubusercontent.com/karlssberg/Motiv/main/icon.png" alt="Motiv logo" width="64" align="left"/>

Motiv

Build Status NuGet codecov

Motiv is a .NET library for building composable, explainable boolean logic — so you never lose the why behind a true or false.

The boolean type has a problem: once evaluated, you lose all context about why the value is true or false.

This is known as the boolean blindness problem:

// Traditional approach - life before Motiv
if (user.Age >= 18 &&
    user.HasValidId &&
    (user.Country == "US" || user.HasInternationalPermit) &&
    !user.IsRestricted)
{
    // Access granted
}
else
{
    // Access denied — but which condition failed?
}

Motiv addresses this by preserving the structure of boolean expressions, so you can recover the underlying causes when you need them:

// With Motiv
var canAccess = Spec
    .From((User user) =>
        user.Age >= 18 &
        user.HasValidId &
        (user.Country == "US" | user.HasInternationalPermit) &
        !user.IsRestricted)
    .Create("can access");

var result = canAccess.Evaluate(user);
result.Satisfied;  // false
result.Assertions; // ["user.Age < 18", "user.HasValidId == false"]

Motiv overloads &, |, ^, and ! so the same operators compose propositions and their results. The short-circuiting && / || are reserved for evaluated results — use .AndAlso() / .OrElse() on propositions. Notice too that each failing clause is rendered in its own terms — user.Age < 18 for the comparison, user.HasValidId == false for the boolean — and passing clauses are dropped from the result.

Core Features

Automatic Propositions

Transform boolean expressions into explanatory logic using the Spec.From() method:

var isEligible = Spec
    .From((Customer c) => c.CreditScore > 600 & c.Income > 100000)
    .Create("eligible for loan");

var result = isEligible.Evaluate(eligibleCustomer);
result.Satisfied;  // true
result.Assertions; // ["c.CreditScore > 600", "c.Income > 100000"]

This takes a lambda expression tree (Expression<Func<T, bool>>) and transforms it into a hierarchy of propositions that mirror the expression's logic.

Manual Composition

For full control, compose propositions manually — no expression trees:

var hasGoodCredit = Spec
    .Build((Customer c) => c.CreditScore > 600)
    .Create("good credit");

var hasIncome = Spec
    .Build((Customer c) => c.Income > 100000)
    .Create("sufficient income");

// create a new proposition
var isEligible = hasGoodCredit.And(hasIncome);

// alternatively, use operator syntax
// var isEligible = hasGoodCredit & hasIncome;

var result = isEligible.Evaluate(eligibleCustomer);
result.Satisfied;  // true
result.Assertions; // ["good credit == true", "sufficient income == true"]
                   // a bare name gets a == true / == false suffix to show the outcome

Custom Assertions

Add readable explanations to your logic:

var hasGoodCredit = Spec
    .Build((Customer c) => c.CreditScore > 600)
    .WhenTrue("has good credit score")
    .WhenFalse("credit score too low")
    .Create();

var result = hasGoodCredit.Evaluate(eligibleCustomer);
result.Satisfied;  // true
result.Assertions; // ["has good credit score"]

Supplying an explicit name via Create("name") instead of parameterless Create() changes the semantics: the name plus a == true/== false suffix becomes the assertion, and the custom strings become metadata, available via Values:

var hasGoodCredit = Spec
    .Build((Customer c) => c.CreditScore > 600)
    .WhenTrue("has good credit score")
    .WhenFalse("credit score too low")
    .Create("good credit");

var result = hasGoodCredit.Evaluate(eligibleCustomer);
result.Satisfied;  // true
result.Assertions; // ["good credit == true"]
result.Values;     // ["has good credit score"]

Query Provider Integration

Propositions built from Spec.From() retain a recoverable expression tree, so they compose into a single predicate that a query provider can translate directly:

var isAdult  = Spec.From((Customer c) => c.Age >= 18).Create("is adult");
var isActive = Spec.From((Customer c) => c.IsActive).Create("is active");

var eligible = isAdult & isActive;

// Translate to SQL via any IQueryable provider (e.g. EF Core)
var customers = dbContext.Customers.Where(eligible);

// Or take the raw expression anywhere expressions are accepted
Expression<Func<Customer, bool>> predicate = eligible.ToExpression();

Asynchronous Propositions

Compose rules that touch databases, APIs, or feature flags — with the same explainable results and true short-circuiting of asynchronous work:

var isAdult = Spec
    .Build((User u) => u.Age >= 18)
    .Create("is adult");

var hasCredit = Spec
    .BuildAsync(async (User u, CancellationToken ct) =>
        await creditApi.CheckAsync(u.Id, ct))
    .WhenTrue("has credit")
    .WhenFalse("no credit")
    .Create();

var canBuy = isAdult.AndAlso(hasCredit);   // credit API never called for minors

var result = await canBuy.EvaluateAsync(user, cancellationToken);
result.Satisfied;  // false
result.Assertions; // ["is adult == false"]

Async and sync propositions compose freely (sync operands are lifted automatically), and independent async operands can opt into concurrent evaluation with AndConcurrently/OrConcurrently/XOrConcurrently.

Side-Effect Observers

Attach logging, metrics, or other side-effects without altering a proposition's behavior:

var observed = isEligible
    .TapWhenTrue((customer, result) =>
        logger.LogInformation("Approved: {Id}", customer.Id))
    .TapWhenFalse((customer, result) =>
        logger.LogWarning("Denied: {Reason}", result.Reason));

// Use exactly like the original — result, assertions, reason are all unchanged
var result = observed.Evaluate(customer);

Observability

Every top-level evaluation reports through OpenTelemetry — a span plus counter/histogram metrics — with no Motiv configuration required. Nothing is emitted until your application subscribes:

builder.Services.AddOpenTelemetry()
    .WithTracing(tracing => tracing.AddSource(MotivTelemetry.SourceName))
    .WithMetrics(metrics => metrics.AddMeter(MotivTelemetry.MeterName));

Collection Logic

Make assertions about collections of items (also known as higher-order logic):

var allNegative = Spec
    .Build((int n) => n < 0)
    .AsAllSatisfied()
    .WhenTrue("all numbers are negative")
    .WhenFalseYield(eval => eval.FalseModels.Select(n => $"{n} is not negative"))
    .Create();

var result = allNegative.Evaluate([-1, 2, 3]);
result.Satisfied;  // false
result.Assertions; // ["2 is not negative", "3 is not negative"]

Live Rules

Hot-swap a running application's rules without redeploying. Declare a rule as a sealed class — the type is its identity — with a compiled spec (or a JSON rule document) as its default implementation:

public sealed class CanCheckoutRule() : Rule<Customer, string>(
    "can-checkout", CanCheckoutSpec, "Gate for the checkout flow");

Wire the rule up and inject the concrete type wherever the decision is made:

builder.Services.AddMotivRules(registry, options)
    .AddRule<CanCheckoutRule>();

app.MapMotivRules("/api/rules");

app.MapPost("/api/checkout", (CanCheckoutRule canCheckout, Customer customer) =>
    Results.Json(canCheckout.Evaluate(customer).Assertions));

PUT /api/rules/rules/can-checkout replaces the implementation live — every evaluation reads an immutable snapshot, writes are protected by optimistic concurrency (409 on a stale baseVersion), and DELETE reverts to the default. Available via the Motiv.Serialization and Motiv.Serialization.AspNetCore packages.

Runtime Propositions

Propositions are the building blocks rules are made of. Register them in C#, or author them at runtime and persist them server-side — either way a rule document references them by name:

builder.Services.AddMotivRules(registry, options)
    // JsonFilePropositionStore is the sample host's own IPropositionStore, not a library type
    .AddPropositions(new JsonFilePropositionStore("propositions.json"))
    .AddRule<CanCheckoutRule>();
// POST /api/rules/propositions
{
  "name": "customer.eligibility.is-eligible",
  "modelType": "customer",
  "document": {
    "rule": { "andAlso": [{ "spec": "customer.is-active" }, { "spec": "customer.is-adult" }] }
  }
}

Names are namespaced with dots, an authored document may override a compiled spec (and DELETE reverts to it), and editing a proposition rebinds every rule and proposition that references it — transactionally, so an edit that would break a dependent is refused whole. Authored propositions are composition only: they combine specs that already exist, because new primitive facts still come from C#. Available via the Motiv.Serialization and Motiv.Serialization.AspNetCore packages.

Quick Start

Install the Motiv NuGet package:

dotnet add package Motiv

or via the NuGet Package Manager:

Install-Package Motiv

Technical Notes

  • Zero additional dependencies on .NET 8+
    • The legacy netstandard2.0 target pulls in System.Diagnostics.DiagnosticSource for telemetry
  • Metadata is evaluated lazily
  • Compatible with both .NET and .NET Framework
  • Zero-allocation fast paths for boolean-only evaluation
  • MIT licensed

Learn More

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 is compatible.  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 is compatible.  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
9.1.0 200 8/11/2026
9.0.0 132 8/10/2026
8.0.0 148 6/28/2026
8.0.0-rc.1 89 6/28/2026
7.4.3 364 8/1/2024
7.4.2 215 7/31/2024
7.4.1 276 7/24/2024
7.4.0 259 7/19/2024
7.3.0 258 6/26/2024
7.2.0 245 6/25/2024
7.1.0 235 6/24/2024
7.0.4 247 6/24/2024
7.0.3 243 6/23/2024
7.0.2 312 6/17/2024
7.0.1 247 6/12/2024
7.0.0 367 5/4/2024
6.0.0 302 4/29/2024 6.0.0 is deprecated because it is no longer maintained.
5.0.0 305 4/28/2024 5.0.0 is deprecated because it is no longer maintained.
4.0.0 314 4/27/2024 4.0.0 is deprecated because it is no longer maintained.
3.1.1 297 4/26/2024 3.1.1 is deprecated because it is no longer maintained.
Loading failed