//
// EventDispatcher.cs
//
// Copyright (c) František Boháček. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Extensions.DependencyInjection;
using Remora.Results;
namespace NosSmooth.Game.Events.Handlers;
///
/// Dispatches with .
///
public class EventDispatcher
{
private readonly IServiceProvider _provider;
///
/// Initializes a new instance of the class.
///
/// The services provider.
public EventDispatcher(IServiceProvider provider)
{
_provider = provider;
}
///
/// Dispatches game responders that are registered in the service collection.
///
/// The event to dispatch.
/// The cancellation token for cancelling the operation.
/// The type of the event.
/// A result that may or may not have succeeded.
public async Task DispatchEvent(TEvent @event, CancellationToken ct = default)
where TEvent : IGameEvent
{
var results = await Task.WhenAll(
_provider
.GetServices>()
.Select(responder => responder.Respond(@event, ct))
);
return results.Length switch
{
0 => Result.FromSuccess(),
1 => results[0],
_ => new AggregateError(results.Cast().ToArray()),
};
}
}