Routya is a fast, lightweight message dispatching library built for .NET applications that use the CQRS pattern.
It provides a flexible way to route requests/responses and notifications to their respective handlers with minimal overhead and high performance.
- β Clean interface-based abstraction for Requests/Responses and Notifications
- π High-performance dispatching - Competitive with MediatR while offering more flexibility
- βοΈ Configurable handler lifetimes - Choose Singleton, Scoped, or Transient per handler
- π§© Optional pipeline behavior support for cross-cutting concerns
- π Supports both sequential and parallel notification dispatching
- π― Multi-framework support - netstandard2.0, netstandard2.1, .NET 8, .NET 9, .NET 10
- πΎ Memory efficient - Zero memory leaks with proper scope management
- β»οΈ Simple to extend and integrate with your existing architecture
- π§ͺ Built with performance and clarity in mind
Latest version:
dotnet add package Routya.Core --version 2.0.01. Pipeline Behavior Delegate Signature Change
The RequestHandlerDelegate<TResponse> now requires a CancellationToken parameter:
// β Old (v1.x)
public delegate Task<TResponse> RequestHandlerDelegate<TResponse>();
// β
New (v2.0)
public delegate Task<TResponse> RequestHandlerDelegate<TResponse>(CancellationToken cancellationToken);Migration Guide:
Update your pipeline behaviors to pass the CancellationToken to the next() delegate:
// β Old code (v1.x)
public async Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
// Your logic before
var result = await next(); // β No parameter
// Your logic after
return result;
}
// β
New code (v2.0)
public async Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
// Your logic before
var result = await next(cancellationToken); // β
Pass cancellationToken
// Your logic after
return result;
}2. Performance Improvements
- Registry-based optimization with smart fallback
- Auto-caching of discovered handlers for improved performance
- 9-10% faster request dispatching with Singleton/Transient handlers
- 30% faster notification dispatching with Singleton sequential handlers
On startup you can define if Routya should create a new instance of the service provider each time it is called or work on the root service provider.
Note!!! By default scope is enabled
Creates a new DI scope for each dispatch
- Safely supports handlers registered as Scoped
- β
Use this if your handlers depend on:
- EF Core DbContext
- IHttpContextAccessor
- IMemoryCache, etc.
builder.Services.AddRoutya(cfg => cfg.Scope = RoutyaDispatchScope.Scoped, Assembly.GetExecutingAssembly());Fastest option
- avoids creating a service scope per dispatch
- Resolves handlers directly from the root IServiceProvider
- β Ideal for stateless handlers that are registered as Transient or Singleton
β οΈ Will fail if your handler is registered as Scoped (e.g., it uses DbContext or IHttpContextAccessor)
builder.Services.AddRoutya(cfg => cfg.Scope = RoutyaDispatchScope.Root, Assembly.GetExecutingAssembly());You can add an auto registration of IRequestHandler, IAsyncRequestHandler and INotificationHandler by adding the executing assembly. This however registers all your request handlers with the default lifetime (Scoped).
Note!!! By default you would have to manually register your Requests/Notifications and Handlers
builder.Services.AddRoutya(cfg => cfg.Scope = RoutyaDispatchScope.Scoped, Assembly.GetExecutingAssembly());Configure handler lifetimes for optimal performance based on your use case:
// Register all handlers as Singleton (fastest, stateless handlers only)
builder.Services.AddRoutya(cfg => cfg.HandlerLifetime = ServiceLifetime.Singleton, Assembly.GetExecutingAssembly());
// Register all handlers as Scoped (default, works with DbContext)
builder.Services.AddRoutya(cfg => cfg.HandlerLifetime = ServiceLifetime.Scoped, Assembly.GetExecutingAssembly());
// Register all handlers as Transient (new instance every time)
builder.Services.AddRoutya(cfg => cfg.HandlerLifetime = ServiceLifetime.Transient, Assembly.GetExecutingAssembly());Use Routya's specialized registration methods for optimal performance:
// Register Routya core services
builder.Services.AddRoutya();
// Use AddRoutyaAsyncRequestHandler for request handlers
builder.Services.AddRoutyaAsyncRequestHandler<CreateProductRequest, Product, CreateProductHandler>(ServiceLifetime.Singleton);
builder.Services.AddRoutyaRequestHandler<GetProductRequest, Product?, GetProductHandler>(ServiceLifetime.Scoped);
// Use AddRoutyaNotificationHandler for notifications
builder.Services.AddRoutyaNotificationHandler<UserRegisteredNotification, SendEmailHandler>(ServiceLifetime.Singleton);
builder.Services.AddRoutyaNotificationHandler<UserRegisteredNotification, LogAuditHandler>(ServiceLifetime.Scoped);Why use these methods?
- β Automatic registry population - Handlers added to high-performance registry
- β 30% faster for notifications (110ns vs 158ns with Singleton)
- β Type-safe - Compile-time verification of handler signatures
- β Flexible lifetimes - Choose Singleton/Scoped/Transient per handler
You can also use standard DI registration - works with auto-caching fallback:
// Register Routya core services (no assembly scanning)
builder.Services.AddRoutya();
// Traditional DI registration (automatically cached to registry on first use)
builder.Services.AddSingleton<IAsyncRequestHandler<CreateProductRequest, Product>, CreateProductHandler>();
builder.Services.AddScoped<IAsyncRequestHandler<GetProductRequest, Product?>, GetProductHandler>();
builder.Services.AddTransient<IAsyncRequestHandler<GetAllProductsRequest, List<Product>>, GetAllProductsHandler>();
// Notification handlers (automatically cached on first publish)
builder.Services.AddSingleton<INotificationHandler<UserRegisteredNotification>, SendEmailHandler>();Trade-off: First call uses standard DI resolution (~5-10% slower), subsequent calls automatically use optimized registry.
Performance Comparison:
- Singleton: ~380 ns (2% slower than MediatR, 50% less memory, best for stateless handlers)
- Transient: ~384 ns (3% slower than MediatR, matches memory, maximum isolation)
- Scoped: ~440 ns (18% overhead, safe for DbContext and scoped dependencies)
Routya lets YOU choose the right lifetime per handler:
- π Singleton for stateless handlers = fastest, least memory
- π Scoped for handlers with DbContext = safe with proper scope management
- π Transient when you need maximum isolation = new instance every time
Routya maintains full backward compatibility with traditional DI registration:
// Traditional registration (still works!)
builder.Services.AddScoped<IAsyncRequestHandler<MyRequest, MyResponse>, MyHandler>();
builder.Services.AddScoped<INotificationHandler<MyNotification>, MyNotificationHandler>();Smart Fallback with Auto-Caching: When handlers aren't found in the registry, Routya automatically:
- Falls back to
GetService/GetServicesresolution (first call) - Adds discovered handlers to the registry (automatic optimization!)
- Uses fast registry-based dispatch for all subsequent calls
This ensures:
- β First call: Fallback resolution (~same speed as traditional)
- β Second+ calls: Registry-optimized dispatch (~28% faster for notifications!)
- β Smooth migration path from older versions
- β Works with existing code without changes
- β Automatic performance improvement after first use
Benchmarks comparing Routya against MediatR 13.1.0 with simple request handlers (BenchmarkDotNet v0.14.0)
Test Environment:
- CPU: 11th Gen Intel Core i7-11800H @ 2.30GHz (8 cores, 16 logical processors)
- RAM: System with AVX-512F support
- OS: Windows 11 (10.0.22623)
- .NET: 8.0.17 (8.0.1725.26602), X64 RyuJIT
- GC: Concurrent Server
| Method | Mean | Ratio | Gen0 | Allocated | Notes |
|---|---|---|---|---|---|
| MediatR_SendAsync | 369.3 ns | 1.00 | 0.0038 | 1016 B | Baseline |
| Routya_Singleton_Send | 333.9 ns | 0.90 | 0.0038 | 1008 B | β‘ 10% faster! |
| Routya_Transient_Send | 336.0 ns | 0.91 | 0.0038 | 1032 B | β‘ 9% faster! |
| Routya_Singleton_SendAsync | 397.7 ns | 1.08 | 0.0048 | 1168 B | 8% overhead for async |
| Routya_Scoped_Send | 395.5 ns | 1.07 | 0.0048 | 1216 B | Scoped DI overhead |
| Routya_Transient_SendAsync | 418.0 ns | 1.13 | 0.0048 | 1192 B | 13% overhead for async |
| Routya_Scoped_SendAsync | 476.4 ns | 1.29 | 0.0048 | 1376 B | Scoped + async overhead |
Key Highlights:
- β Singleton/Transient Send handlers are 9-10% faster than MediatR! π
- β Registry-based dispatch with auto-caching fallback
- β Zero memory leaks with proper scope disposal
- β Fast-path optimization when no behaviors configured
- π― Configurable handler lifetimes (Singleton/Scoped/Transient)
Define a request
public class HelloRequest(string name) : IRequest<string>
{
public string Name { get; } = name;
}Implement the Sync handler ...
public class HelloSyncHandler : IRequestHandler<HelloRequest, string>
{
public string Handle(HelloRequest request)
{
return $"Hello, {request.Name}!";
}
}or Implement the async handler
public class HelloAsyncHandler : IAsyncRequestHandler<HelloRequest, string>
{
public async Task<string> HandleAsync(HelloRequest request, CancellationToken cancellationToken)
{
return await Task.FromResult($"[Async] Hello, {request.Name}!");
}
}Inject the IRoutya interface and dispatch your requests in sync...
public class Example : ControllerBase
{
private readonly IRoutya _dispatcher;
public Example(IRoutya dispatcher)
{
_dispatcher = dispatcher;
}
} _dispatcher.Send<HelloRequest, string>(new HelloRequest("Sync World"));or async
await _dispatcher.SendAsync<HelloRequest, string>(new HelloRequest("Async World"));You can add pipeline behaviors to execute around your requests. These behaviors need to be registered manually and execute in the order they are registered.
services.AddScoped(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));
services.AddScoped(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>)); In the following example the LoggingBehavior will write to console before your request, wait for the request(in the example above first execute the ValidationBehavior and then in the ValidationBehavior it will execute the request) to execute and then write to the console afterward executing the request.
public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
public async Task<TResponse> Handle(
TRequest request,
Routya.Core.Abstractions.RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
Console.WriteLine($"[Logging] β {typeof(TRequest).Name}");
var result = await next(cancellationToken); // Pass cancellationToken to next
Console.WriteLine($"[Logging] β {typeof(TRequest).Name}");
return result;
}
}Benchmarks comparing Routya against MediatR 13.1.0 for notification patterns (BenchmarkDotNet v0.14.0)
| Method | Mean | Ratio | Gen0 | Allocated | Notes |
|---|---|---|---|---|---|
| MediatR_Publish | 157.6 ns | 1.00 | 0.0017 | 440 B | Baseline |
| Routya_Singleton_Sequential | 110.5 ns | 0.70 | 0.0007 | 192 B | β‘ 30% faster, 56% less memory! π |
| Routya_Singleton_Parallel | 143.6 ns | 0.91 | 0.0012 | 312 B | β‘ 9% faster, 29% less memory |
| Routya_Transient_Sequential | 146.0 ns | 0.93 | 0.0010 | 240 B | β‘ 7% faster, 45% less memory |
| Routya_Transient_Parallel | 170.6 ns | 1.08 | 0.0014 | 360 B | 8% slower (parallel overhead) |
| Routya_Scoped_Sequential | 238.1 ns | 1.51 | 0.0014 | 424 B | Scoped DI overhead |
| Routya_Scoped_Parallel | 265.8 ns | 1.69 | 0.0019 | 544 B | Scoped + parallel overhead |
Key Highlights:
- β Singleton sequential: 30% faster than MediatR with 56% less memory (192B vs 440B) π
- β Transient sequential: 7% faster with 45% less memory (240B vs 440B)
- β Registry-based dispatch with auto-caching - Zero GetServices calls after first use
- β Parallel dispatching available with minimal overhead
- β Flexible lifetime management for different use cases
Define your notification
public class UserRegisteredNotification(string email) : INotification
{
public string Email { get; } = email;
}Define your handlers
public class LogAnalyticsHandler : INotificationHandler<UserRegisteredNotification>
{
public async Task Handle(UserRegisteredNotification notification, CancellationToken cancellationToken = default)
{
await Task.Delay(100, cancellationToken);
Console.WriteLine($"π Analytics event logged for {notification.Email}");
}
} public class SendWelcomeEmailHandler : INotificationHandler<UserRegisteredNotification>
{
public async Task Handle(UserRegisteredNotification notification, CancellationToken cancellationToken = default)
{
await Task.Delay(200, cancellationToken);
Console.WriteLine($"π§ Welcome email sent to {notification.Email}");
}
}Inject the IRoutya interface and dispatch your notifications sequentially...
public class Example : ControllerBase
{
private readonly IRoutya _dispatcher;
public Example(IRoutya dispatcher)
{
_dispatcher = dispatcher
}
} await dispatcher.PublishAsync(new UserRegisteredNotification("john.doe@example.com"));or in parallel
await dispatcher.PublishParallelAsync(new UserRegisteredNotification("john.doe@example.com"));The Routya.WebApi.Demo project demonstrates Routya in a production-like environment with:
- β All three handler lifetimes (Singleton, Scoped, Transient)
- β Entity Framework Core with SQL Server
- β Full CRUD operations via RESTful API
- β Real-world performance testing
# Start the Web API
cd Routya.WebApi.Demo
dotnet runThe API will be available at: http://localhost:5079
# Run the comprehensive test script
cd Routya.WebApi.Demo
.\test-requests.ps1The test script demonstrates:
- Singleton handlers: Product creation & stock updates (fastest performance)
- Scoped handlers: Get single product & delete (one instance per HTTP request)
- Transient handlers: Get all products (new instance every call, maximum isolation)
| Method | Endpoint | Handler Lifetime | Description |
|---|---|---|---|
| POST | /api/products |
Singleton | Create new product |
| GET | /api/products |
Transient | Get all products |
| GET | /api/products/{id} |
Scoped | Get product by ID |
| PUT | /api/products/{id}/stock |
Singleton | Update product stock |
| DELETE | /api/products/{id} |
Scoped | Delete product |