Mediator icon indicating copy to clipboard operation
Mediator copied to clipboard

MediatR pre/post/exception handlers

Open martinothamar opened this issue 3 years ago • 1 comments

Currently don't have these. Not sure I want to add these "by default", as they will slow down all pipelines even if not used, but maybe as a separate package? Needs investigation

martinothamar avatar May 26 '21 16:05 martinothamar

I need this too, also behaviors and pre/post processors should be also used for NotificationHandlers. You can add it into PipelineBehavior default implementation and decorate next method like this:

    public class PipelineBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
        where TRequest : IRequest<TResponse>
    {
        private readonly ISet<IPreProcessor<TRequest>> _preProcessors;

        private readonly ISet<IPostProcessor<TRequest,TResponse>> _postProcessors;

        public PipelineBehavior(ISet<IPreProcessor<TRequest>> preProcessors,
            ISet<IPostProcessor<TRequest, TResponse>> postProcessors)
        {
            _preProcessors = preProcessors;
            _postProcessors = postProcessors;
        }

        public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next,
            CancellationToken cancellationToken)
        {
            await ExecutePreProcessorsAsync(request, cancellationToken);
            var response = await next();
            await ExecutePostProcessorsAsync(request, response, cancellationToken);
            return response;
        }

        private async Task ExecutePreProcessorsAsync(TRequest request, CancellationToken cancellationToken)
        {
            foreach (var preProcessor in _preProcessors)
            {
                await preProcessor.ProcessAsync(request, cancellationToken);
            }
        }

        private async Task ExecutePostProcessorsAsync(TRequest request, TResponse response,
            CancellationToken cancellationToken)
        {
            foreach (var postProcessor in _postProcessors)
            {
                await postProcessor.ExecuteAsync(request, response, cancellationToken);
            }
        }
    }

ercinakyuz avatar Nov 08 '22 19:11 ercinakyuz