-
Notifications
You must be signed in to change notification settings - Fork 0
Home
GabrieleToffanin edited this page Feb 21, 2023
·
2 revisions
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 :
-
IRequest<TResult>
where IRequest is an interface that has to be implemented by any kind of class/record
-
IRequestHandler<IRequest<TResult>, TResult>
where the implementing class will need to implement a method likeTask<TResult> HandleAsync(IRequest<TResult> request, CancellationToken cancellationToken)
that has any type of custom logic a developer wants to implement.
-
IMediator
that has a single callable method calledSendAsync(IRequest<TResult> request, CancellationToken cancellationToken)
that will internally dispatch the request to the correctIRequestHandler
.
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;
}
}
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);
}
}
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.