| | 1 | | using planora.Application.Interfaces.Mediator; |
| | 2 | |
|
| | 3 | | namespace planora.Application.Common; |
| | 4 | |
|
| 12 | 5 | | public class Mediator(IServiceProvider serviceProvider) : IMediator |
| | 6 | | { |
| | 7 | | public async Task<TResponse> Query<TResponse>( |
| | 8 | | IQuery<TResponse> query, |
| | 9 | | CancellationToken cancellationToken |
| | 10 | | ) |
| | 11 | | { |
| 4 | 12 | | var handlerType = typeof(IQueryHandler<,>).MakeGenericType(query.GetType(), typeof(TResponse)); |
| 4 | 13 | | var handler = serviceProvider.GetService(handlerType) ?? |
| 4 | 14 | | throw new InvalidOperationException($"No handler registered for {query.GetType().Name}"); |
| | 15 | |
|
| 2 | 16 | | var method = handlerType.GetMethod("Handle") ?? |
| 2 | 17 | | throw new InvalidOperationException($"No 'Handle' method found for {handlerType.Name}"); |
| | 18 | |
|
| 2 | 19 | | return await (Task<TResponse>)method.Invoke(handler, [query, cancellationToken])!; |
| 2 | 20 | | } |
| | 21 | |
|
| | 22 | | public async Task Command(ICommand command, CancellationToken cancellationToken) |
| | 23 | | { |
| 4 | 24 | | var handlerType = typeof(ICommandHandler<>).MakeGenericType(command.GetType()); |
| 4 | 25 | | var handler = serviceProvider.GetService(handlerType) ?? |
| 4 | 26 | | throw new InvalidOperationException($"No handler registered for {command.GetType().Name}"); |
| | 27 | |
|
| 2 | 28 | | var method = handlerType.GetMethod("Handle") ?? |
| 2 | 29 | | throw new InvalidOperationException($"No 'Handle' method found for {handlerType.Name}"); |
| | 30 | |
|
| 2 | 31 | | await (Task)method.Invoke(handler, [command, cancellationToken])!; |
| 2 | 32 | | } |
| | 33 | |
|
| | 34 | | public async Task<TResponse> Command<TResponse>( |
| | 35 | | ICommand<TResponse> command, |
| | 36 | | CancellationToken cancellationToken |
| | 37 | | ) |
| | 38 | | { |
| 4 | 39 | | var handlerType = typeof(ICommandHandler<,>).MakeGenericType(command.GetType(), typeof(TResponse)); |
| 4 | 40 | | var handler = serviceProvider.GetService(handlerType) ?? |
| 4 | 41 | | throw new InvalidOperationException($"No handler registered for {command.GetType().Name}"); |
| | 42 | |
|
| 2 | 43 | | var method = handlerType.GetMethod("Handle") ?? |
| 2 | 44 | | throw new InvalidOperationException($"No 'Handle' method found for {handlerType.Name}"); |
| | 45 | |
|
| 2 | 46 | | return await (Task<TResponse>)method.Invoke(handler, [command, cancellationToken])!; |
| 2 | 47 | | } |
| | 48 | | } |