We all used mediatr many times. In mediatr, we have a very popular behavior feature that allows us to program aop and cross cutting. We have used it many times. But it must have happened to you that you did not combine these behaviors together. Instead of implementing these behaviors each time with our own knowledge, I decided to gather these behaviors together so that we can become better every day and have a collective participation in it. In this package, I tried to collect the best and most useful behaviors of mediatr and Enrich your mediatr project. and put all the useful requirements of the program in it.
Package - MediatR.Useful.Behavior
**Currently, there are 4 very popular and efficient behaviors in this package
- Automatic caching with many features
- Automatic validation
- Automatic logging of unknown errors
- Logging slow commands
Add the package to your application using
dotnet add package MediatR.Useful.Behavior
- AddAllBehaviors: Add all behaviors
- AddCacheBehavior: Add behavior for cache
- AddValidationBehavior: Add validation behavior
- AddUnhandledExceptionBehavior: Add behavior for logging command exceptions
- AddPerformanceBehavior: Add behavior for logging slow commands (commands that take more than 1 second with warning log)
How to activate behaviors in the Startup.cs(or Program.cs) file
// add AddAllBehaviors (cache, validation, unhandled log, performance log)
builder.Services.AddAllBehaviors();
By doing this, behaviors are added to the system. Also, all your validations are added to the system
Your command must use the ICacheableRequest interface. This interface has several properties that must be set
To use cache, you must first introduce cache services to the system
//for in memory cache (RAM)
builder.Services.AddMemoryCache();
//for distribute cache(Redis, Sql, ...)
builder.Services.AddDistributedMemoryCache();
public sealed class TestCommandRq : IRequest<TestCommandRs>, ICacheableRequest<TestCommandRs>
{
public long Amount { get; set; }
public int UserId { get; set; }
public string CacheKey => $"myKey.{UserId}";
[JsonIgnore]
public Func<TestCommandRs, DateTimeOffset> ConditionExpiration => static _ => DateTimeOffset.Now.AddSeconds(10);
public bool UseMemoryCache => false;
}
Properties
- CacheKey: CacheKey is your cache key. You can consider a simple key or the key can be a combination of values
- ConditionExpiration: With ConditionExpiration you can consider a condition for cache expiration. For example, if the user role was equal to the admin value. The cache value should be 10 minutes. otherwise 10 seconds.
- UseMemoryCache: If the specified value of UseMemoryCache is true, it means to use the memory cache. Otherwise, use distributed cache.
- ConditionFroSetCache: You can decide based on your command output whether you need to cache or not. For example, if the output of the user role list service is empty, it will not be cached.
Advanced example:
public sealed class TestCommandAdRq : IRequest<TestCommandRs>, ICacheableRequest<TestCommandRs>
{
public long Amount { get; set; }
public int UserId { get; set; }
public string CacheKey => $"myKey.{UserId}";
[JsonIgnore]
public Func<TestCommandRs, DateTimeOffset> ConditionExpiration => res =>
UserId > 0 ? DateTimeOffset.Now.AddMinutes(10) : DateTimeOffset.Now.AddMinutes(1);
public bool UseMemoryCache => false;
[JsonIgnore]
public Func<TestCommandRs, bool> ConditionFroSetCache => rs => rs.Data?.Any() ?? false;
}
Before executing your command, the system first executes all your validations. For validation, you only need to define your model in this way
public sealed class TestCommandRqValidation : AbstractValidator<TestCommandRq>
{
public TestCommandRqValidation()
{
RuleFor(r => r.Amount).GreaterThan(0);
}
}
If the command takes more than 1 second. The system records a warning log. With complete specifications of the command and input data. example log
Performance Long Running Request: TestCommandRq 3274 millisecond. {"amount":10000,"userId":0,"cacheKey":"myKey.0","useMemoryCache":false}
If an Exception occurs in the command. This behavior records a log with full details. example log
Exception Request: Unhandled Exception for Request TestCommandRq {"amount":0,"userId":0,"cacheKey":"myKey.0","useMemoryCache":false}
FluentValidation.ValidationException: Validation failed:
-- Amount: 'Amount' must be greater than '0'. Severity: Error
at MediatR.Useful.Behavior.Behavior.ValidationBehaviour`2.Handle(TRequest request, RequestHandlerDelegate`1 next, CancellationToken cancellationToken) in F:\Projects\mediatR-useful-behavior\src\MediatR.Useful.Behavior\Behavior\ValidationBehaviour.cs:line 36
at MediatR.Useful.Behavior.Behavior.UnhandledExceptionBehaviour`2.Handle(TRequest request, RequestHandlerDelegate`1 next, CancellationToken cancellationToken) in F:\Projects\mediatR-useful-behavior\src\MediatR.Useful.Behavior\Behavior\UnhandledExceptionBehaviour.cs:line 21
Create an issue if you find a BUG or have a Suggestion or Question. If you want to develop this project :
- Fork it!
- Create your feature branch:
git checkout -b my-new-feature
- Commit your changes:
git commit -am 'Add some feature'
- Push to the branch:
git push origin my-new-feature
- Submit a pull request
If you find this repository useful, please give it a star. Thanks!
MediatR.Useful.Behaviors is Copyright © 2022 Mohsen Rajabi under the MIT License.