Skip to content
GabrieleToffanin edited this page Feb 21, 2023 · 2 revisions

Welcome to MediaSharp 👍💯

Core Functionality

This is library is a wrapper for the mediator pattern that allows better and faster implementation of patterns like CQRS.
Currently the library is divided in 3 principal components :

  1. IRequest<TResult> where IRequest is an interface that has to be implemented by any kind of class/record
  2. IRequestHandler<IRequest<TResult>, TResult> where the implementing class will need to implement a method like Task<TResult> HandleAsync(IRequest<TResult> request, CancellationToken cancellationToken) that has any type of custom logic a developer wants to implement.
  3. IMediator that has a single callable method called SendAsync(IRequest<TResult> request, CancellationToken cancellationToken) that will internally dispatch the request to the correct IRequestHandler.

Request & Handler Example

public class Animal{
    public string Specie { get; set; }
    public int Id { get; set; }
}

public record class GetAnimalsBySpecie(string specie) : IRequest<Animal>;

[CallableHandler]
public partial class GetAnimalBySpecieHandler : IRequestHandler<GetAnimalsBySpecie, Animal>{
    public async Task<Animal> HandleAsync(GetAnimalsBySpecie request, CancellationToken){
        return await //... Whathever the logic is;
    }
}

Usage Example

public class SomeService{
    private readonly IMediator _mediator;
    
    public SomeService(IMediator mediator) {
        this._mediator = mediator;
    }

    public async Task<Animal> DoStuff(CancellationToken cancellationToken){
        return await this._mediator.SendAsync(new GetAnimalsBySpecie("Mammals"), cancellationToken); 
    }
}

Source Generator

MediaSharp uses an implemented by hand SourceGenerator that based on the handlers marked with the [CallabaleHandlerAttribute] will generate some code that will make the library work.
The thing the developer must do is to declare the IRequestHandler implementing class as partial so the Source Generator is
free to extend the class with another partial.