Skip to content

Instantly share code, notes, and snippets.

@mxmissile
Last active April 3, 2025 20:15
Show Gist options
  • Save mxmissile/e3744cbf92e85772132d53226406cd81 to your computer and use it in GitHub Desktop.
Save mxmissile/e3744cbf92e85772132d53226406cd81 to your computer and use it in GitHub Desktop.
public interface IDispatcher
{
Task<TResult> Dispatch<TQuery, TResult>(TQuery operation, CancellationToken cancellation = default) where TQuery : IOperation<TResult>;
Task Publish<TNotification>(TNotification notification, CancellationToken cancellation = default) where TNotification : INotification;
}
public class Dispatcher(IServiceProvider serviceProvider) : IDispatcher
{
public Task<TResult> Dispatch<TOperation, TResult>(TOperation operation, CancellationToken cancellation = default) where TOperation : IOperation<TResult>
{
var handler = serviceProvider.GetRequiredService<IOperationHandler<TOperation, TResult>>();
return handler.Handle(operation, cancellation);
}
public async Task Publish<TNotification>(TNotification notification, CancellationToken cancellation = default) where TNotification : INotification
{
var handlers = serviceProvider.GetServices<INotificationHandler<TNotification>>();
ThrowHelper.ThrowIfNull(handlers);
if (handlers.Any() == false)
{
throw new InvalidOperationException($"no handlers found for {notification}");
}
foreach (var handler in handlers)
{
await handler.Handle(notification, cancellation);
}
}
}
public interface IOperation<out TResult>
{ }
public interface IOperationHandler<in TOperation, TResult> where TOperation : IOperation<TResult>
{
Task<TResult> Handle(TOperation query, CancellationToken cancellation = default);
}
public interface INotification
{ }
public interface INotificationHandler<in TNotification> where TNotification : INotification
{
Task Handle(TNotification notification, CancellationToken cancellation = default);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment