Top Related Projects
Simple, unambitious mediator implementation in .NET
Clean Architecture Solution Template: A proven Clean Architecture Template for ASP.NET Core 9
Assembly scanning and decoration extensions for Microsoft.Extensions.DependencyInjection
This repository contains a suite of libraries that provide facilities commonly needed when creating production-ready applications.
Quick Overview
MediatR is a simple, unambitious mediator implementation in .NET. It supports request/response, commands, queries, notifications, and events. MediatR helps to reduce dependencies between objects by ensuring that objects don't need to know about other objects directly.
Pros
- Simplifies implementation of CQRS (Command Query Responsibility Segregation) pattern
- Promotes loose coupling and separation of concerns
- Easy to use and integrate into existing projects
- Supports dependency injection out of the box
Cons
- Can lead to overuse, resulting in unnecessary complexity for simple applications
- Potential performance overhead for high-frequency operations
- May obscure the flow of the application for developers unfamiliar with the pattern
- Limited built-in support for advanced features like request pipelining (though extensions exist)
Code Examples
- Defining a request and handler:
public class PingRequest : IRequest<string> { }
public class PingHandler : IRequestHandler<PingRequest, string>
{
public Task<string> Handle(PingRequest request, CancellationToken cancellationToken)
{
return Task.FromResult("Pong");
}
}
- Sending a request:
public class SomeService
{
private readonly IMediator _mediator;
public SomeService(IMediator mediator)
{
_mediator = mediator;
}
public async Task<string> DoPing()
{
return await _mediator.Send(new PingRequest());
}
}
- Publishing a notification:
public class ProductAddedNotification : INotification
{
public int ProductId { get; set; }
}
public class EmailNotificationHandler : INotificationHandler<ProductAddedNotification>
{
public Task Handle(ProductAddedNotification notification, CancellationToken cancellationToken)
{
// Send email logic here
return Task.CompletedTask;
}
}
// Publishing the notification
await _mediator.Publish(new ProductAddedNotification { ProductId = 123 });
Getting Started
-
Install the MediatR NuGet package:
dotnet add package MediatR -
Add MediatR to your services in
Startup.csorProgram.cs:services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(Startup).Assembly)); -
Inject
IMediatorinto your classes and start using it to send requests or publish notifications.
Competitor Comparisons
Simple, unambitious mediator implementation in .NET
Pros of MediatR
- Simplified implementation of the mediator pattern
- Supports both synchronous and asynchronous request handling
- Provides pipeline behaviors for cross-cutting concerns
Cons of MediatR
- Potential performance overhead for simple CRUD operations
- May lead to increased complexity in smaller applications
- Requires additional setup and configuration
Code Comparison
MediatR:
public class GetUserByIdQuery : IRequest<User>
{
public int UserId { get; set; }
}
public class GetUserByIdHandler : IRequestHandler<GetUserByIdQuery, User>
{
public Task<User> Handle(GetUserByIdQuery request, CancellationToken cancellationToken)
{
// Implementation
}
}
Both repositories appear to be the same project, as LuckyPennySoftware/MediatR is likely a fork or mirror of the original MediatR repository. Therefore, the code structure and implementation would be identical between the two.
The MediatR library provides a clean separation of concerns by decoupling the request/command objects from their handlers. This approach promotes better organization and maintainability of the codebase, especially in larger applications with complex business logic.
However, for simpler applications or straightforward CRUD operations, using MediatR might introduce unnecessary complexity and a slight performance overhead due to the additional abstraction layer.
Clean Architecture Solution Template: A proven Clean Architecture Template for ASP.NET Core 9
Pros of CleanArchitecture
- Provides a comprehensive template for implementing Clean Architecture principles
- Includes a full set of sample projects and tests, demonstrating best practices
- Offers a more structured approach to organizing code and separating concerns
Cons of CleanArchitecture
- May be overkill for smaller projects or simpler applications
- Steeper learning curve for developers unfamiliar with Clean Architecture concepts
- Requires more initial setup and configuration compared to MediatR
Code Comparison
CleanArchitecture:
public class CreateTodoItemCommand : IRequest<int>
{
public string Title { get; set; }
}
public class CreateTodoItemCommandHandler : IRequestHandler<CreateTodoItemCommand, int>
{
// Implementation
}
MediatR:
public class Ping : IRequest<string> { }
public class PingHandler : IRequestHandler<Ping, string>
{
public Task<string> Handle(Ping request, CancellationToken cancellationToken)
{
return Task.FromResult("Pong");
}
}
Both repositories utilize the Mediator pattern, but CleanArchitecture provides a more comprehensive structure for implementing Clean Architecture principles, while MediatR focuses specifically on the mediator implementation. CleanArchitecture offers a fuller template with sample projects, whereas MediatR is more lightweight and focused on its core functionality.
Assembly scanning and decoration extensions for Microsoft.Extensions.DependencyInjection
Pros of Scrutor
- Focused on assembly scanning and dependency injection, providing more flexibility in service registration
- Supports attribute-based registration, allowing for easier configuration of services
- Offers advanced filtering options for more granular control over service registration
Cons of Scrutor
- Limited to dependency injection scenarios, whereas MediatR provides a full mediator implementation
- Requires more manual configuration for complex scenarios compared to MediatR's out-of-the-box functionality
- Lacks built-in support for request/response patterns and pipeline behaviors
Code Comparison
Scrutor:
services.Scan(scan => scan
.FromAssemblyOf<ITransientService>()
.AddClasses(classes => classes.AssignableTo<ITransientService>())
.AsImplementedInterfaces()
.WithTransientLifetime());
MediatR:
services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(Startup).Assembly));
Scrutor focuses on flexible service registration, while MediatR provides a more opinionated approach to implementing the mediator pattern. Scrutor offers greater control over dependency injection, but MediatR simplifies the implementation of request/response patterns and pipeline behaviors. The choice between the two depends on the specific needs of your project and the level of control you require over service registration and messaging patterns.
This repository contains a suite of libraries that provide facilities commonly needed when creating production-ready applications.
Pros of extensions
- Broader scope, offering a wide range of extensions for .NET applications
- Official Microsoft repository, ensuring long-term support and compatibility
- More frequent updates and contributions from a larger community
Cons of extensions
- Less focused on a specific pattern or architecture
- May require more setup and configuration for specific use cases
- Potentially steeper learning curve due to the breadth of features
Code Comparison
MediatR:
public class PingHandler : IRequestHandler<Ping, string>
{
public Task<string> Handle(Ping request, CancellationToken cancellationToken)
{
return Task.FromResult("Pong");
}
}
extensions:
public class CustomMiddleware
{
private readonly RequestDelegate _next;
public CustomMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
// Custom logic here
await _next(context);
}
}
The code examples showcase the different focus areas of each project. MediatR emphasizes the mediator pattern for handling requests, while extensions provides tools for building custom middleware and other .NET application components.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
MediatR
Simple mediator implementation in .NET
In-process messaging with no dependencies.
Supports request/response, commands, queries, notifications and events, synchronous and async with intelligent dispatching via C# generic variance.
Examples in the wiki.
Installing MediatR
You should install MediatR with NuGet:
Install-Package MediatR
Or via the .NET Core command line interface:
dotnet add package MediatR
Either commands, from Package Manager Console or .NET Core CLI, will download and install MediatR and all required dependencies.
Using Contracts-Only Package
To reference only the contracts for MediatR, which includes:
IRequest(including generic variants)INotificationIStreamRequest
Add a package reference to MediatR.Contracts
This package is useful in scenarios where your MediatR contracts are in a separate assembly/project from handlers. Example scenarios include:
- API contracts
- GRPC contracts
- Blazor
Registering with IServiceCollection
MediatR supports Microsoft.Extensions.DependencyInjection.Abstractions directly. To register various MediatR services and handlers:
services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining<Startup>());
or with an assembly:
services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(Startup).Assembly));
This registers:
IMediatoras transientISenderas transientIPublisheras transientIRequestHandler<,>concrete implementations as transientIRequestHandler<>concrete implementations as transientINotificationHandler<>concrete implementations as transientIStreamRequestHandler<>concrete implementations as transientIRequestExceptionHandler<,,>concrete implementations as transientIRequestExceptionAction<,>)concrete implementations as transient
This also registers open generic implementations for:
INotificationHandler<>IRequestExceptionHandler<,,>IRequestExceptionAction<,>
To register behaviors, stream behaviors, pre/post processors:
services.AddMediatR(cfg => {
cfg.RegisterServicesFromAssembly(typeof(Startup).Assembly);
cfg.AddBehavior<PingPongBehavior>();
cfg.AddStreamBehavior<PingPongStreamBehavior>();
cfg.AddRequestPreProcessor<PingPreProcessor>();
cfg.AddRequestPostProcessor<PingPongPostProcessor>();
cfg.AddOpenBehavior(typeof(GenericBehavior<,>));
});
With additional methods for open generics and overloads for explicit service types.
Setting the license key
You can set the license key when registering MediatR:
services.AddMediatR(cfg =>
{
cfg.LicenseKey = "<license key here>";
})
Or if not using Microsoft.Extensions.DependencyInjection:
Mediator.LicenseKey = "<license key here>";
[!TIP] The license key does not need to be set on client applications (such as Blazor WASM). Turn off the license warning by configuring logging in your logging start configuration:
builder.Logging.AddFilter("LuckyPennySoftware.MediatR.License", LogLevel.None);
You can register for your license key at MediatR.io
Top Related Projects
Simple, unambitious mediator implementation in .NET
Clean Architecture Solution Template: A proven Clean Architecture Template for ASP.NET Core 9
Assembly scanning and decoration extensions for Microsoft.Extensions.DependencyInjection
This repository contains a suite of libraries that provide facilities commonly needed when creating production-ready applications.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot