21 Mar 2024




Advanced

In ASP.NET Core WebAPI, the term "Mediator" typically refers to the MediatR library, which is a popular implementation of the mediator pattern in .NET. The mediator pattern is a behavioral design pattern that helps to reduce the direct coupling between components by introducing a mediator object that handles communication between them.

Here's a brief overview of how MediatR works in ASP.NET Core WebAPI:

  1. Installation: First, you need to install the MediatR NuGet package into your ASP.NET Core WebAPI project. You can do this using the NuGet Package Manager or by running the following command in the Package Manager Console:

    Install-Package MediatR
    
  2. Defining Requests and Handlers: In MediatR, you typically define two main types: Requests and Handlers. Requests represent the messages or commands that your application sends to be processed, and Handlers are responsible for processing those requests.

    • Define your request classes by inheriting from IRequest<TResponse>. For example:

      public class GetCustomerQuery : IRequest<Customer>
      {
          public int CustomerId { get; set; }
      }
      
    • Define handler classes that implement IRequestHandler<TRequest, TResponse>. For example:

      public class GetCustomerQueryHandler : IRequestHandler<GetCustomerQuery, Customer>
      {
          private readonly ICustomerRepository _repository;
      
          public GetCustomerQueryHandler(ICustomerRepository repository)
          {
              _repository = repository;
          }
      
          public async Task<Customer> Handle(GetCustomerQuery request, CancellationToken cancellationToken)
          {
              return await _repository.GetCustomerById(request.CustomerId);
          }
      }
      
  3. Registering MediatR: In your ASP.NET Core Startup class, you need to register MediatR and its dependencies in the service container:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMediatR(typeof(Startup));
        // Other service registrations
    }
    
  4. Using Mediator: Finally, you can inject an instance of IMediator into your controllers or services and use it to send requests and receive responses. For example:

    public class CustomersController : ControllerBase
    {
        private readonly IMediator _mediator;
    
        public CustomersController(IMediator mediator)
        {
            _mediator = mediator;
        }
    
        [HttpGet("{id}")]
        public async Task<ActionResult<Customer>> GetCustomer(int id)
        {
            var query = new GetCustomerQuery { CustomerId = id };
            var customer = await _mediator.Send(query);
            if (customer == null)
            {
                return NotFound();
            }
            return customer;
        }
    }
    

With this setup, when a request is made to the GetCustomer endpoint, the controller sends a GetCustomerQuery request to MediatR. MediatR then finds the appropriate handler (GetCustomerQueryHandler), executes it, and returns the result to the controller, which then sends it back as an HTTP response.

Using MediatR in ASP.NET Core WebAPI can help keep your code organized, maintainable, and testable by promoting the separation of concerns and reducing dependencies between components.