A simple, lightweight implementation of an in-memory publisher/subscriber pattern for .NET applications. SimpleTransit provides a clean and efficient way to implement message-driven architectures using either direct notification handling or queued message processing.
- Dual Messaging Patterns: Support for both immediate notifications and queued message processing
- Dependency Injection Integration: Seamless integration with Microsoft.Extensions.DependencyInjection
- ASP.NET Core Ready: Built-in support for HTTP context-aware scoping
- Type-Safe: Strongly-typed message handling with generic interfaces
- Minimal Dependencies: Lightweight with minimal external dependencies
- Multi-Target Support: Compatible with .NET 8.0, 9.0 and 10.0
SimpleTransit is available as NuGet packages:
dotnet add package SimpleTransitdotnet add package SimpleTransit.AbstractionsAdd SimpleTransit to your dependency injection container:
var builder = WebApplication.CreateBuilder(args);
// Register SimpleTransit and automatically discover handlers/consumers
builder.Services.AddSimpleTransit(options =>
{
options.RegisterServicesFromAssemblyContaining<Program>();
});
var app = builder.Build();// For notifications (direct handling)
public record PersonCreated(string FirstName, string LastName, string? City);
// For queued messages (implement IMessage)
public record ProductCreated(string Name, string Description, double Price) : IMessage;public class PersonCreatedNotificationHandler(ILogger<PersonCreatedNotificationHandler> logger) : INotificationHandler<PersonCreated>
{
public async Task HandleAsync(PersonCreated message, CancellationToken cancellationToken)
{
logger.LogInformation("Person created: {FirstName} {LastName} from {City}",
message.FirstName, message.LastName, message.City);
// Handle the notification immediately
await DoSomethingAsync(message);
}
}public class ProductCreatedConsumer(ILogger<ProductCreatedConsumer> logger) : IConsumer<ProductCreated>
{
public async Task HandleAsync(ProductCreated message, CancellationToken cancellationToken)
{
logger.LogInformation("Processing product: {ProductName}...", message.Name);
// Simulate processing
await Task.Delay(1000, cancellationToken);
logger.LogInformation("Product processed: {ProductName}", message.Name);
}
}app.MapPost("/api/people", async (PersonCreated person, INotificationPublisher notificationPublisher) =>
{
// Publish notification (handled immediately)
await notificationPublisher.NotifyAsync(person);
return TypedResults.Ok();
});
app.MapPost("/api/products", async (ProductCreated product, IMessagePublisher messagePublisher) =>
{
// Publish message (queued for processing)
await messagePublisher.PublishAsync(product);
return TypedResults.Accepted();
});SimpleTransit supports two distinct messaging patterns:
- Purpose: Immediate handling of events
- Interface:
INotificationHandler<T> - Publisher:
INotificationPublisher - Execution: Notifications are handled in the same context of the caller that invokes
NotifyAsync - Use Cases: Logging, immediate side effects, real-time updates
- Purpose: Reliable, background processing
- Interface:
IConsumer<T>whereT : IMessage - Publisher:
IMessagePublisher - Execution: Asynchronous queue processing
- Use Cases: Long-running operations, batch processing, reliable delivery
builder.Services.AddSimpleTransit(options =>
{
// Mark that you have notification handlers
options.UseNotificationHandlers();
// Mark that you have message consumers
options.UseMessageConsumers();
});
// Manually register your handlers
builder.Services.AddTransient<INotificationHandler<PersonCreated>, PersonCreatedNotificationHandler>();
builder.Services.AddTransient<IConsumer<ProductCreated>, ProductCreatedConsumer>();builder.Services.AddSimpleTransit(options =>
{
// Register all handlers and consumers from specified assembly
options.RegisterServicesFromAssemblyContaining<Program>();
// Or from a specific assembly
options.RegisterServicesFromAssembly(typeof(MyHandler).Assembly);
// With optional filtering
options.RegisterServicesFromAssembly(
assembly,
type => type.Namespace?.StartsWith("MyApp.Handlers") == true);
});Multiple notification handlers can be registered for the same message type:
public class EmailNotificationHandler : INotificationHandler<PersonCreated>
{
public async Task HandleAsync(PersonCreated message, CancellationToken cancellationToken)
{
// Send email
}
}
public class AuditNotificationHandler : INotificationHandler<PersonCreated>
{
public async Task HandleAsync(PersonCreated message, CancellationToken cancellationToken)
{
// Log to audit system
}
}Exceptions thrown by notification handlers are forwarded to the caller, allowing for proper error handling. Exceptions from background message consumers are not propagated.
try
{
await notificationPublisher.NotifyAsync(message);
}
catch (Exception ex)
{
// Handle errors from any of the notification handlers
logger.LogError(ex, "Error processing notification");
}SimpleTransit properly handles service scoping, especially in ASP.NET Core applications:
public class DatabaseHandler(MyDbContext context) : INotificationHandler<PersonCreated>
{
public async Task HandleAsync(PersonCreated message, CancellationToken cancellationToken)
{
// Use scoped DbContext safely
context.People.Add(new Person { Name = message.FirstName });
await context.SaveChangesAsync(cancellationToken);
}
}- Choose the Right Pattern: Use notifications for immediate actions, messages for background processing
- Keep Handlers Focused: Each handler should have a single responsibility
- Handle Errors Gracefully: Always consider error scenarios in your handlers
- Use Cancellation Tokens: Support cancellation for long-running operations
- Leverage Dependency Injection: Take advantage of scoped services for database operations
- Consider Performance: Notifications are executed synchronously, so keep them fast
A complete sample application is available in the samples/SimpleTransitSample directory, demonstrating:
- Web API integration
- Both notification and message patterns
- Service registration and configuration
- Real-world usage scenarios
To run the sample:
cd samples/SimpleTransitSample
dotnet runThen navigate to the Swagger UI at the URL specified in the console to test the API endpoints.
Contributions are welcome! Please feel free to submit issues, feature requests, or pull requests.
- Fork the repository and create a feature branch
- Follow existing code style and conventions
- Add tests for new functionality
- Update documentation as needed
- Ensure all tests pass before submitting
# Clone the repository
git clone https://github.com/marcominerva/SimpleTransit.git
cd SimpleTransit
# Build the solution
dotnet build
# Run tests (if available)
dotnet testWhen reporting issues, please include:
- .NET version
- SimpleTransit version
- Minimal reproduction example
- Expected vs actual behavior
This project is licensed under the MIT License.