MediatR.Useful.Behavior
1.0.4
See the version list below for details.
dotnet add package MediatR.Useful.Behavior --version 1.0.4
NuGet\Install-Package MediatR.Useful.Behavior -Version 1.0.4
<PackageReference Include="MediatR.Useful.Behavior" Version="1.0.4" />
paket add MediatR.Useful.Behavior --version 1.0.4
#r "nuget: MediatR.Useful.Behavior, 1.0.4"
// Install MediatR.Useful.Behavior as a Cake Addin #addin nuget:?package=MediatR.Useful.Behavior&version=1.0.4 // Install MediatR.Useful.Behavior as a Cake Tool #tool nuget:?package=MediatR.Useful.Behavior&version=1.0.4
<p align="center"> <a href="https://www.buymeacoffee.com/mohsenrajabi" target="_blank"> <img src="https://cdn.buymeacoffee.com/buttons/v2/default-orange.png" height="61" width="194" /> </a> </p>
The best behaviors of MediatR ( Enrich your mediatr project )
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
To use, you can add all behaviors at once. Or add each separately
- 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
Cache
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;
}
Validation
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);
}
}
Performance Log
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}
Unhandled Log
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
Contributing
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
Give a Star! ⭐️
If you find this repository useful, please give it a star. Thanks!
License
MediatR.Useful.Behaviors is Copyright © 2022 Mohsen Rajabi under the MIT License.
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. |
.NET Core | netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
.NET Standard | netstandard2.1 is compatible. |
MonoAndroid | monoandroid was computed. |
MonoMac | monomac was computed. |
MonoTouch | monotouch was computed. |
Tizen | tizen60 was computed. |
Xamarin.iOS | xamarinios was computed. |
Xamarin.Mac | xamarinmac was computed. |
Xamarin.TVOS | xamarintvos was computed. |
Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.1
- FluentValidation (>= 11.4.0)
- MediatR (>= 11.1.0)
- Microsoft.Extensions.Caching.Abstractions (>= 7.0.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 7.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 7.0.0)
- Scrutor (>= 4.2.0)
- System.Text.Json (>= 7.0.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
v1.0.4
Breaking changes
- add UnhandledExceptionBehaviour
- add PerformanceBehaviour
v1.0.3
Breaking changes
- update doc
- add example
v1.0.2
Breaking changes
- add Scrutor for automatic validator added
v1.0.1
Breaking changes
- clean up dependency
v1.0.0
Breaking changes
- add cache behavior
- add valdiation behavior