As the name suggests, a new library that extends MediatR with integrated PipelineBehavior:
- Performance Logger
- MemoryCache
- Validation with FluentValidation
- Retry Pattern with Polly
We recommend using NuGet:
Install-Package One.More.Lib.For.MediatR
Or via the .NET Core command line interface:
dotnet add package One.More.Lib.For.MediatR
The simplest way:
builder.Services.AddMediatRExtensions(cfg => cfg.PerformanceLoggerSupport = true);
If you want to configure it:
builder.Services.AddMediatRExtensions(cfg => cfg.AddPerformanceLoggerSupport(500));
Nothing to do. Requests exceeding th threshold will be logged.
The simplest way:
builder.Services.AddMediatRExtensions(cfg => cfg.MemoryCacheSupport = true);
If you want a complete configuration:
builder.Services.AddMediatRExtensions(cfg => cfg.AddMemoryCacheSupport(slidingExpiration: TimeSpan.FromMinutes(10), priority: CacheItemPriority.Low));
All the possible options are:
-
DateTimeOffset? AbsoluteExpiration
-
TimeSpan? AbsoluteExpirationRelativeToNow
-
TimeSpan? SlidingExpiration
-
CacheItemPriority Priority
You can also create a specific configuration with the same options for a given request:
builder.Services.AddMediatRExtensions(cfg =>
{
cfg.AddMemoryCacheSupport(slidingExpiration: TimeSpan.FromMinutes(10), priority: CacheItemPriority.Low);
cfg.AddMemoryCacheSupportOverrideFor<GiveRequest>(priority: CacheItemPriority.High);
}
Just add [MemoryCache] attribute on requests classes or records.
[MemoryCache]
public class GetUserByName : IRequest<User?>
{
public string Name { get; set; }
}
There is not simplest way because you need to enter the assemblies to be scanned for FluentValidation:
builder.Services.AddMediatRExtensions(cfg => cfg.AddFluentValidationSupport(new[] { typeof(Program).Assembly }));
Nothing to do, just create Validation rules. If a rule is not respected a ValidationException will be thrown.
The simplest way:
builder.Services.AddMediatRExtensions(cfg => cfg.RetrySupport = true);
If you want to configure it:
builder.Services.AddMediatRExtensions(cfg => cfg.AddRetrySupport(retryCount: 3, retryDelay: 100));
- For example, when you call on external resources and the infrastructure can sometimes have temporarey failures.
- Or when you want to deal with the database and there may be temporary conflicts.
Just add [RetryPolicy] attribute on requests classes or records.
[RetryPolicy]
public class GetProduct : IRequest<Product>
{
public Guid ProductId { get; set; }
}
Or you can override default values by passing them in the RetryPolicy Attribute
[RetryPolicy(OverrideRetryCount = true, RetryCount = 5)]
public class GetProduct : IRequest<Product>
{
public Guid ProductId { get; set; }
}
[RetryPolicy(OverrideRetryDelay = true, RetryDelay = 200)]
public class GetProduct : IRequest<Product>
{
public Guid ProductId { get; set; }
}