RoyceLark.DispatchR
1.0.0
dotnet add package RoyceLark.DispatchR --version 1.0.0
NuGet\Install-Package RoyceLark.DispatchR -Version 1.0.0
<PackageReference Include="RoyceLark.DispatchR" Version="1.0.0" />
<PackageVersion Include="RoyceLark.DispatchR" Version="1.0.0" />
<PackageReference Include="RoyceLark.DispatchR" />
paket add RoyceLark.DispatchR --version 1.0.0
#r "nuget: RoyceLark.DispatchR, 1.0.0"
#:package RoyceLark.DispatchR@1.0.0
#addin nuget:?package=RoyceLark.DispatchR&version=1.0.0
#tool nuget:?package=RoyceLark.DispatchR&version=1.0.0
RoyceLark.DispatchR - All-in-One Mediator with AI/ML 🚀
RoyceLark.DispatchR is a complete, production-ready mediator library for .NET 9 and .NET 10 with built-in AI and ML capabilities - all in a single, unified package. No need for multiple packages!
✨ Why RoyceLark.DispatchR?
- 📦 Single Package - Everything you need in one unified library
- 🤖 AI Built-In - Intelligent caching and telemetry for AI requests
- 🧠 ML Ready - Machine learning predictions and AutoML training included
- ⚡ High Performance - Optimized for .NET 9 and .NET 10 with minimal allocations
- 🔄 Full-Featured - CQRS, pub/sub, streaming, and pipeline behaviors
- 🎯 RoyceLark.DispatchR Compatible - Drop-in replacement for MediatR
📦 Installation
dotnet add package RoyceLark.DispatchR
That's it! No need for separate AI or ML packages - everything is included!
🚀 Quick Start
1. Register RoyceLark.DispatchR (One Line!)
builder.Services.AddDispatchR(config =>
{
config.RegisterServicesFromAssemblyContaining<Program>();
// AI and ML features are enabled by default!
});
2. Create a Request and Handler
// Define request
public record GetUserQuery(int UserId) : IRequest<UserDto>;
// Define handler
public class GetUserHandler : IRequestHandler<GetUserQuery, UserDto>
{
public async Task<UserDto> Handle(GetUserQuery request, CancellationToken ct)
{
// Your logic here
return new UserDto(request.UserId, "John Doe", "john@example.com");
}
}
3. Use the Mediator
public class UserController : ControllerBase
{
private readonly IMediator _mediator;
public UserController(IMediator mediator) => _mediator = mediator;
[HttpGet("{id}")]
public async Task<IActionResult> GetUser(int id)
{
var user = await _mediator.Send(new GetUserQuery(id));
return Ok(user);
}
}
🎯 Features
Core Mediator Features
✅ Request/Response Pattern (CQRS)
public record CreateOrderCommand(int CustomerId) : IRequest<int>;
public record GetOrderQuery(int OrderId) : IRequest<OrderDto>;
✅ Pub/Sub Notifications
public record OrderCreatedEvent(int OrderId) : INotification;
// Multiple handlers automatically called in parallel
public class SendEmailHandler : INotificationHandler<OrderCreatedEvent> { }
public class UpdateInventoryHandler : INotificationHandler<OrderCreatedEvent> { }
✅ Streaming Support
public record StreamDataRequest(int Count) : IStreamRequest<DataItem>;
await foreach (var item in _mediator.CreateStream(new StreamDataRequest(100)))
{
Console.WriteLine(item);
}
✅ Pipeline Behaviors
public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CT ct)
{
// Before handler logic
var response = await next();
// After handler logic
return response;
}
}
🛡️ Resilience & Reliability
✅ Automatic Retry with Exponential Backoff
public class GetDataRequest : IRequest<Data>, IRetriableRequest
{
public RetryPolicy GetRetryPolicy() => new() { MaxRetries = 3 };
}
✅ Timeout Management
public class LongRequest : IRequest<Result>, ITimeoutRequest
{
public TimeSpan Timeout => TimeSpan.FromSeconds(30);
}
✅ Exception Handling
- Comprehensive exception types
- Detailed error messages
- Proper exception propagation
⚡ Performance & Scalability
✅ Response Caching
public class GetProductQuery : IRequest<Product>, ICacheableRequest<Product>
{
public string GetCacheKey() => $"product:{ProductId}";
public TimeSpan? GetCacheDuration() => TimeSpan.FromMinutes(10);
}
✅ Performance Monitoring
// Automatic performance tracking
// Logs slow requests (>1s)
// Custom metrics collection support
✅ Memory Optimized
- Minimal allocations
- Handler caching
- Efficient streaming
🔐 Security
✅ Authorization
public class DeleteCommand : IRequest<bool>, IAuthorizedRequest
{
public IEnumerable<IAuthorizationRequirement> GetAuthorizationRequirements()
{
yield return new RoleRequirement("Admin");
}
}
✅ Request Validation
public class CreateUserValidator : IValidator<CreateUserCommand>
{
public async Task<ValidationResult> ValidateAsync(CreateUserCommand request, CT ct)
{
if (string.IsNullOrEmpty(request.Email))
return ValidationResult.Failure("Email", "Email is required");
return ValidationResult.Success();
}
}
💾 Data Management
✅ Transaction Support
public class CreateOrderCommand : IRequest<int>, ITransactionalRequest
{
// Automatic commit on success, rollback on failure
}
🤖 AI Features (Built-In!)
AI-Enhanced Requests with Automatic Caching:
public class AnalyzeSentimentRequest : AIRequest<SentimentResult>
{
public string Text { get; set; }
public AnalyzeSentimentRequest()
{
Temperature = 0.7f; // AI model settings
MaxTokens = 1000; // All included!
}
}
// Automatic caching and telemetry - no extra code needed!
var result = await _mediator.Send(new AnalyzeSentimentRequest { Text = "..." });
Built-in AI Features:
- ✅ Intelligent response caching
- ✅ Performance telemetry
- ✅ Request tracking
- ✅ Model configuration
🧠 ML Features (Built-In!)
ML Predictions:
public class PredictPriceRequest : MLRequest<PricePrediction>
{
public HouseData Input { get; set; }
public PredictPriceRequest()
{
ModelPath = "models/price-model.zip";
}
}
var prediction = await _mediator.Send(new PredictPriceRequest { Input = houseData });
AutoML Training:
services.AddDispatchR(config =>
{
config.EnableML = true;
config.MLSeed = 42; // For reproducibility
});
// Use the built-in training service
var trainingService = serviceProvider.GetRequiredService<IMLModelTrainingService>();
var model = await trainingService.TrainClassificationModelAsync<Data, Prediction>(
trainingData,
"LabelColumn",
maxExplorationTimeInSeconds: 60
);
Built-in ML Features:
- ✅ ML.NET integration
- ✅ AutoML support
- ✅ Model caching
- ✅ Request validation
📊 Configuration
builder.Services.AddDispatchR(config =>
{
// Assemblies to scan
config.RegisterServicesFromAssemblyContaining<Program>();
config.RegisterServicesFromAssemblies(typeof(Handlers).Assembly);
// AI Features (enabled by default)
config.EnableAI = true;
config.EnableAICaching = true; // Smart caching
config.EnableAITelemetry = true; // Performance tracking
// ML Features (enabled by default)
config.EnableML = true;
config.EnableMLValidation = true; // Request validation
config.MLSeed = 42; // Reproducibility
// Pipeline Behaviors
config.RegisterPipelineBehaviors = true;
});
🎭 Complete Example
using RoyceLark.DispatchR;
using RoyceLark.DispatchR.AI;
using RoyceLark.DispatchR.ML;
using RoyceLark.DispatchR.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
// Single package - all features included!
builder.Services.AddDispatchR(config =>
{
config.RegisterServicesFromAssemblyContaining<Program>();
});
builder.Services.AddControllers();
var app = builder.Build();
// Basic request
app.MapPost("/greet", async (IMediator mediator, GreetRequest req) =>
{
var response = await mediator.Send(req);
return Results.Ok(response);
});
// AI request (automatic caching + telemetry)
app.MapPost("/ai-analyze", async (IMediator mediator, AnalyzeRequest req) =>
{
var result = await mediator.Send(req);
return Results.Ok(result);
});
// Pub/sub event
app.MapPost("/order", async (IMediator mediator, OrderCreatedEvent evt) =>
{
await mediator.Publish(evt); // All handlers called automatically
return Results.Ok();
});
// Streaming
app.MapGet("/stream/{count}", async (IMediator mediator, int count) =>
{
var items = new List<int>();
await foreach (var item in mediator.CreateStream(new StreamRequest(count)))
items.Add(item);
return Results.Ok(items);
});
app.Run();
📚 Architecture
DispatchR (Single Package)
├── Core/
│ ├── IMediator, Mediator
│ ├── IRequest, IRequestHandler
│ ├── INotification, INotificationHandler
│ ├── IStreamRequest, IStreamRequestHandler
│ └── IPipelineBehavior
├── AI/
│ ├── AIRequest<T>
│ ├── AICachingBehavior
│ ├── AITelemetryBehavior
│ └── IAICacheService
├── ML/
│ ├── MLRequest<T>
│ ├── MLPredictionHandler
│ ├── MLValidationBehavior
│ └── IMLModelTrainingService
└── DependencyInjection/
└── ServiceCollectionExtensions
🆚 vs MediatR
| Feature | RoyceLark.DispatchR | MediatR |
|---|---|---|
| Basic CQRS | ✅ | ✅ |
| Pipeline Behaviors | ✅ | ✅ |
| Notifications | ✅ | ✅ |
| Streaming | ✅ | ✅ |
| AI Integration | ✅ Built-in | ❌ Manual |
| ML Support | ✅ Built-in | ❌ Manual |
| Caching | ✅ Built-in | ❌ Manual |
| Validation | ✅ Built-in | ❌ Manual |
| Retry Logic | ✅ Built-in | ❌ Manual |
| Timeout Management | ✅ Built-in | ❌ Manual |
| Transactions | ✅ Built-in | ❌ Manual |
| Authorization | ✅ Built-in | ❌ Manual |
| Performance Monitoring | ✅ Built-in | ❌ Manual |
| .NET 10 Optimized | ✅ | ⚠️ |
| Single Package | ✅ | ❌ Multiple |
🎓 Best Practices
- Use AI/ML features when needed - They're already there!
- Keep handlers focused - One responsibility per handler
- Leverage pipeline behaviors - For cross-cutting concerns
- Use notifications for side effects - Decouple operations
- Enable caching for AI - It's automatic and smart
- Test handlers independently - They're easy to unit test
📖 Documentation
🔧 Building from Source
# Clone repository
git clone https://github.com/roycelark/dispatchr.git
# Build
dotnet build
# Run tests
dotnet test
# Run sample
cd samples/DispatchR.Sample
dotnet run
📄 License
MIT License - See LICENSE file
🤝 Contributing
Contributions welcome! Please open an issue or PR.
💡 Support
- 📖 Documentation
- 💬 Discussions
- 🐛 Issues
⭐ Why RoyceLark.DispatchR?
Because you deserve a modern, all-in-one mediator that includes AI and ML capabilities out of the box, without juggling multiple packages!
Made with ❤️ for the .NET community
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | 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. |
-
net10.0
- Microsoft.Extensions.AI.Abstractions (>= 10.2.0)
- Microsoft.Extensions.Caching.Memory (>= 10.0.2)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.2)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.2)
- Microsoft.ML (>= 5.0.0)
- Microsoft.ML.AutoML (>= 0.23.0)
-
net9.0
- Microsoft.Extensions.AI.Abstractions (>= 10.2.0)
- Microsoft.Extensions.Caching.Memory (>= 10.0.2)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.2)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.2)
- Microsoft.ML (>= 5.0.0)
- Microsoft.ML.AutoML (>= 0.23.0)
- System.Text.Json (>= 10.0.2)
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 |
|---|---|---|
| 1.0.0 | 121 | 1/20/2026 |