Skip to content

Example of Request pipeline

Kirill edited this page Oct 21, 2020 · 1 revision

Write request for create user (required)

public sealed class Request : IRequest<User> 
{
     public string Name { get; }

     public string Email { get; }

     public Request(string name, string email) 
     {
          Name = name;
          Email = email
     }
}

Write pre processor for validate data

public class PreProcessor : IRequestPreProcessor<Request>
{
    public Task Process(Request request, CancellationToken cancellationToken)
    {
        if (string.IsNullOrWhitespace(request.Name) || string.IsNullOrWhitespace(request.Email))
        {
            throw new InvalidDataException();  
        }
    }
}

Write handler for create user by request (required)

internal sealed class Handler : IRequestHandler<Request, User> 
{
     private readonly DataContext _context;

     public Handler(DataContext context) 
     {
          _context = context;
     }

     public Task<User> Handle(Request request, CancellationToken cancellationToken)
     {
          var entry = _context.Users.Add(new User { Name = request.Name, Email = request.Email );

          await _context.SaveChangesAsync(cancellationToken);
          
          return entry.Entity;
     }
}

Write post processor for publish notification about user is created

internal sealed class PostProcessor : IRequestPostProcessor<Request, User> 
{
    private readonly IMediator _mediator;

    public PostProcessor(IMediator mediator) 
    {
        _mediator = mediator;
    }
    
    public Task Process(Request request, User response, CancellationToken cancellationToken)
    {
        return _mediator.Publish(new UserCreatedNotification(response.Id), cancellationToken);
    }
}