Skip to content

Middleware

Middleware

diagram

Middleware is the concept that refers to a layer of code that lies between your handler and the caller using the IMediator. It provides you with a before and after hook to do things like logging, caching, error handling, etc. You can mutate the results or short circuit it if necessary.

Our middleware follows the same general principles from ASP.NET Core. Shiny Mediator supports middleware for both requests and events, however, they are two separate pipelines.

namespace Shiny.Mediator;
public delegate Task EventHandlerDelegate();
public interface IEventMiddleware<TEvent> where TEvent : IEvent
{
Task Process(
IEvent @event,
EventHandlerDelegate next,
IEventHandler<TEvent> eventHandler,
CancellationToken cancellationToken
);
}
public delegate Task<TResult> RequestHandlerDelegate<TResult>();
public interface IRequestMiddleware<TRequest, TResult> where TRequest : IRequest<TResult>
{
Task<TResult> Process(
TRequest request,
RequestHandlerDelegate<TResult> next,
IRequestHandler<TRequest, TResult> requestHandler,
CancellationToken cancellationToken
);
}

As with ASP.NET Core, when you’re implementing middleware, you have a next parameter that you must call to continue the pipeline.

Registering Middleware

TODO

Out of the Box Middleware

We have some “out of the box” middleware that we think is pretty awesome for apps.

(Request) Caching

Features

TODO

  • Caching Based on Connectivity - it will keep using cache if offline even if expired
[Cache(MaxAgeSeconds = 60, Storage = StoreType.File, OnlyForOffline = false)]
public class MyRequestHandler : IRequestHandler<MyRequest, MyResponse>
{
public async Task<MyResponse> Handle(MyRequest request, CancellationToken ct)
{
// do something async here
}
}

(Request) User Notification Exception Handling

TODO

(Request) Slow Execution Monitoring

TODO

(Events) Main Thread Execution

TODO

(Events) Error Handling

TODO