MediatR.Useful.Behavior 1.0.4

There is a newer version of this package available.
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                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="MediatR.Useful.Behavior" Version="1.0.4" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add MediatR.Useful.Behavior --version 1.0.4                
#r "nuget: MediatR.Useful.Behavior, 1.0.4"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// 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                

GitHub license Nuget Nuget

<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 :

  1. Fork it!
  2. Create your feature branch: git checkout -b my-new-feature
  3. Commit your changes: git commit -am 'Add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. 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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.0.6 177 5/16/2024
1.0.5 880 12/25/2022
1.0.4 299 12/24/2022
1.0.3 320 12/22/2022
1.0.2 319 12/22/2022
1.0.1 321 12/22/2022
1.0.0 324 12/22/2022

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