[Dot Net Core](Graphic series ) 17. MediatR — PreProcess and PostProcess

Czxdas
2 min readDec 2, 2022

--

In the content of MediatR-IRequest, the operation of IRequest is shown, as shown in the figure below:

and working show:

https://ithelp.ithome.com.tw/articles/10293809

There are PreProcess and PostProcess at the end of the operation (lower right in the picture above). The preprocess can do things such as write logs, data verification and verification, etc., and the postprocess can do things such as write logs and store transaction records in Database.

Suppose we take the example of executing the following:

var result = await _mediator.Send(new GetCustomersQuery());

The class inherits the interface IRequest, and Customer passes the data medium for the data model in it:

public class GetCustomersQuery : IRequest<List<Customer>>
{

public void PreProcess()
{
PreProcessCollection.Instance[PreProcessCollection.Instance.Count] =
new { datetime = DateTime.Now, Message = "do pre-process stuff....." };
}

public void PostProcess(int count)
{
PostProcessCollection.Instance[PostProcessCollection.Instance.Count] =
new { datetime = DateTime.Now, Message = $" do post-process stuff.....result total number is {count}" };
}


}

Executed Handler class:

public class GetCustomersQueryHandler : IRequestHandler<GetCustomersQuery, List<Customer>>
{
public async Task<List<Customer>> Handle(GetCustomersQuery request, CancellationToken cancellationToken)
{
return _repository.GetAll<Customer>().ToList();
}
}

The difference from the previous example is that in [IRequest], the fifth step is to use ServiceFactory to implement entities from the registered service IPipelineBehavior<TRequest, TResponse>, and combine these entities with IRequestHandler<GetCustomersQuery, List> Execute its Handle function.

The order of execution is RequestPreProcessorBehavior.Handle -> GetCustomersQueryHandler.Handle -> RequestExceptionProcessorBehavior.Handle -> RequestExceptionActionProcessorBehavior.Handle -> RequestPostProcessorBehavior.Handle

However, RequestPreProcessorBehavior.Handle and RequestPostProcessorBehavior.Handle are the first and last to be executed, so they can be used to perform pre- and final actions respectively.

When ServiceFactory implements an entity from a registered service IPipelineBehavior<TRequest, TResponse> , its constructor is also injected into the service.

RequestPreProcessorBehavior will inject IRequestPreProcessor entity, RequestPostProcessorBehavior will inject IRequestPostProcessor<TRequest, TResponse> entity.

Therefore, developers can design class for these two services.

--

--