Giter VIP home page Giter VIP logo

engrajabi / mediatr.useful.behaviors Goto Github PK

View Code? Open in Web Editor NEW
25.0 2.0 3.0 97 KB

MediatR Useful Behavior In this repository; I tried to write and save the best popular behaviors that we use in mediatr in a professional way. And they will be added and improved over time. The best library to complete mediatr

License: MIT License

C# 99.05% Batchfile 0.95%
behavior cache caching logging mediatr mediatr-extension mediatr-behavior behaviors enrich mediator

mediatr.useful.behaviors's Introduction

GitHub license Nuget Nuget

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.

mediatr.useful.behaviors's People

Contributors

dependabot[bot] avatar engrajabi avatar mohammadaminpourmoradian avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.