Table of Contents

PatternKit Generators

PatternKit includes a Roslyn incremental generator package (PatternKit.Generators) that emits pattern implementations at compile time. Use it when you want predictable generated code, design-time diagnostics, and less handwritten pattern scaffolding.

When to Use

  • You already express intent with attributes and want the compiler to write the implementation.
  • You need synchronous APIs, ValueTask-first async APIs, or both.
  • You want deterministic codegen that is friendly to trimming and AOT scenarios.

Package & Setup

  1. Add the analyzer package to your project:

    dotnet add package PatternKit.Generators
    
  2. Ensure the project targets netstandard2.0+ (for libraries) or any modern .NET target (for apps). No runtime references are required.

  3. Mark your types with the attributes below; the generator produces partial classes at compile time.

Available Generators

Creational Patterns

Generator Description Attribute
Abstract Factory Product-family factories with optional IServiceProvider construction [GenerateAbstractFactory]
Builder GoF-aligned builders with mutable or state-projection models, sync/async pipelines [GenerateBuilder]
Factory Method Keyed dispatcher from a static partial class [FactoryMethod]
Factory Class GoF-style factory mapping keys to products [FactoryClass]
Object Pool Bounded pooled-resource factories with optional reset hooks [GenerateObjectPool]
Prototype Clone/deep-copy generation for types [Prototype]
Singleton Thread-safe singleton accessors with optional factory hooks [Singleton]

Structural Patterns

Generator Description Attribute
Decorator Base decorator classes with forwarding and composition helpers [GenerateDecorator]
Facade Simplified interfaces to complex subsystems [GenerateFacade]
Adapter Adapter implementations from mapping attributes [GenerateAdapter]
Bridge Abstraction/implementation pairs with forwarding [BridgeAbstraction] / [BridgeImplementor]
Composite Component trees and traversal helpers [CompositeComponent]
Flyweight Keyed flyweight factories and caches [Flyweight]
Proxy Proxy implementations with interception support [GenerateProxy]

Behavioral Patterns

Generator Description Attribute
Chain Chain-of-responsibility pipelines [Chain]
Command Command objects and invokers [Command]
Composer Pipeline composition from ordered steps [Composer]
Interpreter DSL rule factories for terminal and non-terminal expressions [GenerateInterpreter]
Iterator Enumerable/async-enumerable iteration helpers [Iterator]
Memento Immutable snapshots with optional undo/redo history [Memento]
Null Object Deterministic no-op implementations for optional contracts [GenerateNullObject]
Observer Event hubs and observer dispatch [ObserverHub]
State Machine Deterministic finite state machines [StateMachine]
Strategy Predicate-based dispatch with fluent builder [GenerateStrategy]
Specification Named business-rule registries [GenerateSpecificationRegistry]
Repository In-memory repository factories from key selectors [GenerateRepository]
Anti-Corruption Layer External-to-domain translation boundaries with validation [GenerateAntiCorruptionLayer]
Activity Tracker Active-work tracker gates for loading and readiness workflows [GenerateActivityTracker]
Manual Task Gate Human approval gates for workflow pauses and manual decisions [GenerateManualTaskGate]
Workflow Orchestration Ordered workflow factories from annotated step methods [WorkflowOrchestration]
Snapshot / Checkpoint Management Replay checkpoint manager factories for resumable processors [GenerateSnapshotCheckpointManager]
Eventual Consistency Monitor Watermark lag monitor factories for projection convergence [GenerateEventualConsistencyMonitor]
Timeout Manager Deadline registry for expiring pending workflow work [GenerateTimeoutManager]
Audit Log Append-only audit log factories from key selectors [GenerateAuditLog]
Unit of Work Ordered commit and rollback units [GenerateUnitOfWork]
Compensating Transaction Reversible business transactions from annotated step methods [GenerateCompensatingTransaction]
Data Mapper Domain/data model mapper factories [GenerateDataMapper]
Identity Map Scoped object identity caches from key selectors [GenerateIdentityMap]
Lazy Load Deferred value factories with caching, TTL, and invalidation [GenerateLazyLoad]
Ports and Adapters Hexagonal inbound adapters, application ports, and outbound adapters [GeneratePortsAndAdapters]
Materialized View Event projection read-model factories from handlers [GenerateMaterializedView]
Transaction Script Typed application workflow factories [GenerateTransactionScript]
Service Layer Application operation boundary factories [GenerateServiceLayerOperation]
Domain Event Domain event dispatcher factories [GenerateDomainEventDispatcher]
Table Data Gateway Row gateway factories from key selectors [GenerateTableDataGateway]
Event Sourcing Append-only event store factories [GenerateEventStore]
Feature Toggle Contextual feature toggle factories [GenerateFeatureToggleSet]
Template Method Template method skeletons with hook points [Template]
Visitor Type-safe visitor implementations [GenerateVisitor]

Messaging

Generator Description Attribute
Dispatcher Mediator pattern with commands, notifications, and streams [GenerateDispatcher]
Message Channel Typed channel factories for in-process message queues [GenerateMessageChannel]
Message Bus Topic bus topology factories over message channels [GenerateMessageBus]
Messaging Bridge Channel-to-bus bridge factories for topology boundaries [GenerateMessagingBridge]
Correlation Identifier Correlation factories for request/reply and workflow message traces [GenerateCorrelationIdentifier]
Message History Message handling history factories for auditable envelopes [GenerateMessageHistory]
Channel Purger Channel maintenance purger factories for in-process message queues [GenerateChannelPurger]
Invalid Message Channel Invalid-message channel builder factories for validation boundaries [GenerateInvalidMessageChannel]
Polling Consumer Pull-based message consumer factories [GeneratePollingConsumer]
Event-Driven Consumer Push-based message consumer factories [GenerateEventDrivenConsumer]
Durable Subscriber Checkpointed replay subscriber factories [GenerateDurableSubscriber]
Channel Adapter External DTO to message-channel adapter factories [GenerateChannelAdapter]
Messaging Gateway Typed request/response gateway factories [GenerateMessagingGateway]
Service Activator Message-to-service operation factories [GenerateServiceActivator]
Message Envelope Required message metadata contracts [GenerateMessageEnvelope]
Message Translator Partner and transport event normalization [GenerateMessageTranslator]
Content Enricher Ordered async payload enrichment pipelines [GenerateContentEnricher]
Canonical Data Model Source-to-canonical contract normalization [GenerateCanonicalDataModel]
Event-Carried State Transfer State-rich event projection factories [GenerateEventCarriedStateTransfer]
Event Notification Compact event notification factories [GenerateEventNotification]
Claim Check External payload storage references [GenerateClaimCheck]
Dead Letter Channel Failed-message capture and replay handoff [GenerateDeadLetterChannel]
Content Router Content-based message routing factories [GenerateContentRouter]
Message Filter Named allow-rule filters for message consumers [GenerateMessageFilter]
Message Expiration Deadline stamping and stale-message evaluation policies [GenerateMessageExpiration]
Guaranteed Delivery Durable delivery queue factories with lease and retry settings [GenerateGuaranteedDelivery]
Message Store Message audit, lookup, and replay store factories [GenerateMessageStore]
Wire Tap Side-channel message observability factories [GenerateWireTap]
Control Bus Operational command bus factories for message processors [GenerateControlBus]
Scatter-Gather Fan-out request and reply aggregation factories [GenerateScatterGather]
Resequencer Sequence-aware buffering factories for out-of-order messages [GenerateResequencer]
Recipient List Recipient fan-out factories [GenerateRecipientList]
Splitter / Aggregator Split/rejoin message routing factories [GenerateSplitter] / [GenerateAggregator]
Routing Slip Ordered message itinerary factories [GenerateRoutingSlip]
Saga Typed process-manager transition factories [GenerateSaga]
Mailbox Serialized in-process inbox factories [GenerateMailbox]
Backpressure Admission-control policy factories for saturated work boundaries [GenerateBackpressurePolicy]
Change Data Capture Ordered mutation capture pipeline factories [GenerateChangeDataCapture]
Reliability Pipeline Idempotent receiver, inbox, and outbox factories [GenerateReliabilityPipeline]
Backplane Topology Request/reply routes and publish/subscribe endpoint topology [GenerateBackplaneTopology]

Cloud And Resilience

Generator Description Attribute
Retry Bounded retry policy factories for transient results and exceptions [GenerateRetryPolicy]
Circuit Breaker Dependency isolation policy factories with open and half-open states [GenerateCircuitBreakerPolicy]
Bulkhead Bounded concurrency and queue isolation policy factories [GenerateBulkheadPolicy]
Queue Load Leveling Bounded worker queue policy factories [GenerateQueueLoadLevelingPolicy]
Health Endpoint Monitoring Typed service health endpoint factories [GenerateHealthEndpoint]
Priority Queue Business-priority queue factories [GeneratePriorityQueue]
Cache-Aside Read-through cache policy factories with TTL and cache predicates [GenerateCacheAsidePolicy]
Cache Stampede Protection Keyed single-flight policy factories for suppressing duplicate cache-miss loads [GenerateCacheStampedeProtection]
Read-Through / Write-Through Cache Cache-backed repository policy factories with coordinated read and write paths [GenerateReadWriteThroughCachePolicy]
Rate Limiting Key-partitioned fixed-window rate limit policy factories [GenerateRateLimitPolicy]
External Configuration Store Typed centralized configuration loaders [GenerateExternalConfigurationStore]
Gateway Aggregation API gateway response composition factories [GenerateGatewayAggregation]
Gateway Routing API gateway route dispatch factories [GenerateGatewayRouting]
Strangler Fig Legacy-to-modern migration routing factories [GenerateStranglerFig]
Sidecar Companion behavior pipeline factories [GenerateSidecar]
Backends for Frontends Client-specific facade factories [GenerateBackendsForFrontends]
Ambassador Outbound connectivity wrapper factories [GenerateAmbassador]
Leader Election Lease-backed active worker factories [GenerateLeaderElection]
Distributed Lock Resource lease lock factories [GenerateDistributedLock]
Scheduler Agent Supervisor Scheduled worker supervision factories [GenerateSchedulerAgentSupervisor]

Quick Reference

Creational

// Builder - fluent object construction
[GenerateBuilder]
public partial class Person { public string Name { get; set; } }

// Factory - keyed product creation
[GenerateFactory(typeof(INotification), typeof(NotificationKind))]
public abstract partial class NotificationFactory { }

// Abstract factory - generated product families
[GenerateAbstractFactory(typeof(Platform))]
[AbstractFactoryProduct(Platform.Windows, typeof(IButton), typeof(WindowsButton))]
[AbstractFactoryProduct(Platform.Linux, typeof(IButton), typeof(LinuxButton))]
public static partial class PlatformWidgets { }

// Prototype - cloning
[Prototype]
public partial class Document { }

Structural

// Decorator - add behavior via wrapping
[GenerateDecorator]
public interface IRepository { }

// Facade - simplify subsystem access
[GenerateFacade]
public static partial class BillingHost { }

// Proxy - control access/add interception
[GenerateProxy]
public interface IService { }

Behavioral

// Composer - pipeline middleware
[Composer]
public partial class Pipeline
{
    [ComposeStep(0)] public T Step(in T x, Func<T, T> next) => next(x);
    [ComposeTerminal] public T End(in T x) => x;
}

// Memento - state snapshots
[Memento(GenerateCaretaker = true)]
public partial class EditorState { }

// Strategy - predicate dispatch
[GenerateStrategy("Router", typeof(Request), StrategyKind.Action)]
public partial class Router { }

// Interpreter - generated DSL rule factory
[GenerateInterpreter(typeof(PricingContext), typeof(decimal))]
public static partial class PricingRules { }

// Template Method - algorithm skeleton
[Template]
public abstract partial class DataProcessor { }

// Anti-corruption layer - external model boundary
[GenerateAntiCorruptionLayer(typeof(LegacyOrderDto), typeof(CommerceOrder))]
public static partial class LegacyOrderAcl { }

// Message translator - partner event normalization
[GenerateMessageTranslator(typeof(PartnerOrderAccepted), typeof(CommerceOrderAccepted))]
public static partial class PartnerOrderTranslator { }

// Event-carried state transfer - state-rich projection events
[GenerateEventCarriedStateTransfer(typeof(InventoryAdjustedEvent), typeof(string), typeof(InventoryReadModel))]
public static partial class InventoryStateTransfer { }

// Event notification - compact event signals
[GenerateEventNotification(typeof(OrderAccepted), typeof(string))]
public static partial class OrderAcceptedNotification { }

// Lazy load - deferred value factory
[GenerateLazyLoad(typeof(CustomerProfile), LoaderMethodName = "LoadProfileAsync", TimeToLiveMilliseconds = 300000)]
public static partial class CustomerProfileLazyLoad { }

// Claim check - external payload storage reference
[GenerateClaimCheck(typeof(LargeOrderDocument), StoreName = "document-archive")]
public static partial class LargeDocumentClaims { }

// Dead-letter channel - failed message capture and replay handoff
[GenerateDeadLetterChannel(typeof(FulfillmentCommand), ChannelName = "fulfillment-dead-letter")]
public static partial class FulfillmentDeadLetters { }

// Visitor - type-safe double dispatch
[GenerateVisitor]
public interface IDocumentVisitor { }

Messaging

// Dispatcher - mediator pattern
[assembly: GenerateDispatcher(Namespace = "MyApp", Name = "Dispatcher")]

// Message envelope - generated required-header contract
[GenerateMessageEnvelope(typeof(OrderAccepted))]
[MessageEnvelopeHeader("correlation-id", typeof(string))]
public static partial class OrderAcceptedEnvelope { }

// Content router - generated first-match route factory
[GenerateContentRouter(typeof(Order), typeof(string))]
public static partial class OrderRouter { }

// Competing consumers - generated shared work group builder
[GenerateCompetingConsumerGroup(typeof(OrderWork), typeof(OrderResult), MaxConcurrentDeliveries = 4)]
public static partial class OrderConsumers { }

// Pipes and filters - generated ordered pipeline builder
[GeneratePipesAndFiltersPipeline(typeof(OrderContext), PipelineName = "fulfillment")]
public static partial class OrderPipeline { }

// Splitter and aggregator - generated split/rejoin factories
[GenerateSplitter(typeof(Order), typeof(OrderLine))]
public static partial class OrderSplitter { }

[GenerateAggregator(typeof(string), typeof(OrderLine), typeof(decimal))]
public static partial class OrderLineAggregator { }

// Mailbox - generated serialized inbox factory
[GenerateMailbox(typeof(OrderWork), Capacity = 32, BackpressurePolicy = "Wait")]
public static partial class OrderMailbox { }

// Backpressure - generated admission-control policy
[GenerateBackpressurePolicy(typeof(CheckoutAdmission), Capacity = 8, Mode = "Wait", WaitTimeoutMilliseconds = 50)]
public static partial class CheckoutBackpressurePolicy { }

// Change data capture - generated mutation capture pipeline
[GenerateChangeDataCapture(typeof(ProductMutation), typeof(ProductChanged), MapperMethodName = "Map")]
public static partial class ProductCatalogCdc { }

// Reliability pipeline - generated idempotent receiver, inbox, and outbox factories
[GenerateReliabilityPipeline(typeof(AcceptOrder), typeof(string), typeof(OrderAccepted))]
public static partial class OrderReliability { }

// Durable subscriber - generated checkpointed replay subscriber
[GenerateDurableSubscriber(typeof(OrderShipmentEvent), SubscriberName = "shipment-projection")]
public static partial class OrderShipmentSubscriber { }

// Backplane topology - generated request/reply and pub/sub host wiring
[GenerateBackplaneTopology(typeof(OrderBackplaneServices), HostBuilderType = typeof(OrderBackplaneHostBuilder))]
[BackplaneRequestReply(typeof(SubmitOrder), typeof(OrderAccepted), "orders", nameof(OrderBackplaneServices.AcceptAsync))]
[BackplaneSubscription(typeof(OrderSubmitted), "orders.submitted", "audit-service", nameof(OrderBackplaneServices.AuditAsync))]
public static partial class OrderBackplane { }

// Routing slip - generated ordered itinerary factory
[GenerateRoutingSlip(typeof(Order))]
public static partial class OrderSlip { }

// Saga - generated process-manager factory
[GenerateSaga(typeof(OrderSagaState))]
public static partial class OrderSaga { }

Cloud And Resilience

// Retry - generated bounded retry policy
[GenerateRetryPolicy(typeof(InventoryResponse), MaxAttempts = 3, BackoffFactor = 2)]
public static partial class InventoryRetryPolicy { }

// Circuit breaker - generated dependency isolation policy
[GenerateCircuitBreakerPolicy(typeof(FulfillmentResponse), FailureThreshold = 2, BreakDurationMilliseconds = 30000)]
public static partial class FulfillmentCircuitBreakerPolicy { }

// Bulkhead - generated bounded concurrency policy
[GenerateBulkheadPolicy(typeof(ShippingAllocation), MaxConcurrency = 4, MaxQueueLength = 16, QueueTimeoutMilliseconds = 250)]
public static partial class ShippingBulkheadPolicy { }

// Cache-aside - generated read-through cache policy
[GenerateCacheAsidePolicy(typeof(ProductReadModel), TimeToLiveMilliseconds = 300000)]
public static partial class ProductCatalogCachePolicy { }

// Rate limiting - generated tenant or key budget policy
[GenerateRateLimitPolicy(typeof(SearchResponse), PermitLimit = 2, WindowMilliseconds = 60000)]
public static partial class ProductSearchRateLimitPolicy { }

// Gateway aggregation - generated downstream response composition
[GenerateGatewayAggregation(typeof(CustomerDashboardRequest), typeof(CustomerDashboardResponse))]
public static partial class CustomerDashboardGateway { }

// Gateway routing - generated route dispatch
[GenerateGatewayRouting(typeof(ProductGatewayRequest), typeof(ProductGatewayResponse))]
public static partial class ProductGatewayRouting { }

// Strangler Fig - generated legacy-to-modern migration routing
[GenerateStranglerFig(typeof(CheckoutMigrationRequest), typeof(CheckoutMigrationResponse))]
public static partial class CheckoutMigration { }

// Sidecar - generated companion behavior around a primary handler
[GenerateSidecar(typeof(OrderTelemetryRequest), typeof(OrderTelemetryResponse))]
public static partial class OrderTelemetrySidecar { }

Examples

See Generator Examples and Source Generator Application Suite for:

  • DI module wiring and generated host builders
  • Orchestrated application startup steps
  • Generated facades, proxies, observers, mementos, state machines, strategies, visitors, and messaging factories
  • Real-world usage patterns validated by PatternKit.Examples.Tests

Troubleshooting

See Troubleshooting for common issues and diagnostic codes.

See Also