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!
- 📦 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
dotnet add package RoyceLark.DispatchRThat's it! No need for separate AI or ML packages - everything is included!
builder.Services.AddDispatchR(config =>
{
config.RegisterServicesFromAssemblyContaining<Program>();
// AI and ML features are enabled by default!
});// 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");
}
}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);
}
}✅ 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;
}
}✅ 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
✅ 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
✅ 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();
}
}✅ Transaction Support
public class CreateOrderCommand : IRequest<int>, ITransactionalRequest
{
// Automatic commit on success, rollback on failure
}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 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
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;
});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();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
| 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 |
- 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
# Clone repository
git clone https://github.com/roycelark/dispatchr.git
# Build
dotnet build
# Run tests
dotnet test
# Run sample
cd samples/DispatchR.Sample
dotnet runMIT License - See LICENSE file
Contributions welcome! Please open an issue or PR.
- 📖 Documentation
- 💬 Discussions
- 🐛 Issues
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