PatternKit Documentation

Fluent Design Patterns for Modern .NET
Fluent APIs and incremental source generators for classic patterns in modern .NET.


๐ŸŒŸ Overview

PatternKit is a library that implements classic Gang of Four design patterns with fluent runtime helpers and Roslyn incremental source generators.

Instead of heavyweight base classes and repeated handwritten scaffolding, PatternKit favors:

  • Fluent builders and chainable DSLs
  • Source generators that emit deterministic compile-time code
  • AOT-friendly generated implementations where pattern shape is known at design time
  • Strong typing and discoverable APIs
  • Readable BDD-style tests using TinyBDD

๐Ÿš€ Getting Started

Install the NuGet package:

dotnet add package PatternKit

For reusable IServiceCollection registrations:

dotnet add package PatternKit.Hosting.Extensions

Example: Strategy<TIn, TOut>

using PatternKit.Behavioral.Strategy;

var classify = Strategy<int, string>.Create()
    .When(i => i > 0).Then(i => "positive")
    .When(i => i < 0).Then(i => "negative")
    .Default(_ => "zero")
    .Build();

Console.WriteLine(classify.Execute(42));  // positive
Console.WriteLine(classify.Execute(-7));  // negative
Console.WriteLine(classify.Execute(0));   // zero

Example: TryStrategy<TIn, TOut>

var parser = TryStrategy<string, int>.Create()
    .Always((in string s, out int r) => int.TryParse(s, out r))
    .Finally((in string _, out int r) => { r = 0; return true; })
    .Build();

if (parser.Execute("123", out var value))
    Console.WriteLine(value); // 123

๐Ÿ“š Available Patterns

PatternKit covers 121 production-readiness patterns with fluent APIs, source-generated routes where applicable, IoC integration examples, TinyBDD coverage, and BenchmarkDotNet coverage-matrix validation:

Category Count Patterns
Application Architecture 29 Activity Tracker, Aggregate Root, Anti-Corruption Layer, Audit Log, Bounded Context, Context Map, CQRS, Data Mapper, Domain Event, Domain Service, Event Sourcing, Eventual Consistency Monitor, Feature Toggle, Identity Map, Lazy Load, Manual Task Gate, Materialized View, Ports and Adapters, Repository, Service Layer, Snapshot / Checkpoint Management, Specification, Table Data Gateway, Timeout Manager, Transaction Script, Unit of Work, Compensating Transaction, Value Object, Workflow Orchestration
Behavioral 12 Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Null Object, Observer, State, Strategy, Template Method, Visitor
Cloud Architecture 21 Ambassador, Backends for Frontends, Bulkhead, Cache-Aside, Cache Stampede Protection, Circuit Breaker, Distributed Lock / Lease, External Configuration Store, Gateway Aggregation, Gateway Routing, Health Endpoint Monitoring, Leader Election, Priority Queue, Queue-Based Load Leveling, Rate Limiting, Read-Through Cache, Retry, Scheduler Agent Supervisor, Sidecar, Strangler Fig, Write-Through Cache
Creational 6 Abstract Factory, Builder, Factory Method, Object Pool, Prototype, Singleton
Enterprise Integration 42 Aggregator, Canonical Data Model, Change Data Capture, Channel Adapter, Channel Purger, Claim Check, Competing Consumers, Content Enricher, Content-Based Router, Control Bus, Correlation Identifier, Dead Letter Channel, Durable Subscriber, Dynamic Router, Event Notification, Event-Carried State Transfer, Event-Driven Consumer, Guaranteed Delivery, Invalid Message Channel, Mailbox, Message Bus, Message Channel, Message Envelope, Message Expiration, Message Filter, Message History, Message Store, Message Translator, Messaging Bridge, Messaging Gateway, Pipes and Filters, Polling Consumer, Publish-Subscribe, Recipient List, Request-Reply, Resequencer, Routing Slip, Saga / Process Manager, Scatter-Gather, Service Activator, Splitter, Wire Tap
Messaging Reliability 4 Backpressure, Idempotent Receiver, Inbox, Outbox
Structural 7 Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy

See Benchmarks and Benchmark Results for published fluent-vs-source-generated timing, allocation snapshots, and the full pattern/generator matrix.

๐Ÿ› ๏ธ Source Generators

Prefer compile-time code generation over handwritten boilerplate? See the Generators section for:

  • Builder โ€” Fluent object construction with validation
  • Factory โ€” Keyed product creation
  • Adapter โ€” Interface and member adaptation
  • Bridge โ€” Abstraction/implementation separation
  • Chain โ€” Request pipelines
  • Command โ€” Command wrappers and dispatch
  • Composite โ€” Tree-shaped object models
  • Decorator โ€” Base classes with forwarding
  • Facade โ€” Simplified subsystem interfaces
  • Flyweight โ€” Keyed flyweight factories
  • Iterator โ€” Enumerable adapters
  • Observer โ€” Event hubs and subscriptions
  • Proxy โ€” Access control and interception
  • Singleton โ€” Instance accessors
  • State Machine โ€” State transitions
  • Composer โ€” Pipeline middleware composition
  • Memento โ€” State snapshots and undo/redo
  • Strategy โ€” Predicate-based dispatch
  • Dispatcher โ€” Mediator pattern (CQRS)
  • Visitor โ€” Type-safe double dispatch

All generators produce deterministic code with no runtime dependency on PatternKit.

Each supported pattern ships with tests, API documentation, and examples where applicable.

  • Fluent API: readable and composable (.When(...), .Then(...), .Finally(...))
  • Strongly-typed handlers using in parameters
  • Performance focus โ€” explicit code paths with no reflection-based dispatch in generated implementations
  • XML docs and examples available in API reference

๐Ÿงช Testing Philosophy

All patterns are tested with TinyBDD, enabling Gherkin-like, human-readable scenarios:

[Feature("Strategy")]
public class StrategyTests : TinyBddXunitBase
{
    [Scenario("Positive/negative classification")]
    [Fact]
    public async Task ClassificationWorks()
    {
        await Given("a strategy with three branches", BuildStrategy)
            .When("executing with 5", s => s.Execute(5))
            .Then("result should be 'positive'", r => r == "positive")
            .AssertPassed();
    }
}