~ruther/NosSmooth

ref: 53001defff272403865de322c5d8efa078f90926 NosSmooth/Core/NosSmooth.Game/Events/Handlers/EventDispatcher.cs -rw-r--r-- 1.7 KiB
53001def — František Boháček feat: add game event responders and logic 3 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//
//  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;

/// <summary>
/// Dispatches <see cref="IGameResponder"/> with <see cref="IGameEvent"/>.
/// </summary>
public class EventDispatcher
{
    private readonly IServiceProvider _provider;

    /// <summary>
    /// Initializes a new instance of the <see cref="EventDispatcher"/> class.
    /// </summary>
    /// <param name="provider">The services provider.</param>
    public EventDispatcher(IServiceProvider provider)
    {
        _provider = provider;
    }

    /// <summary>
    /// Dispatches game responders that are registered in the service collection.
    /// </summary>
    /// <param name="event">The event to dispatch.</param>
    /// <param name="ct">The cancellation token for cancelling the operation.</param>
    /// <typeparam name="TEvent">The type of the event.</typeparam>
    /// <returns>A result that may or may not have succeeded.</returns>
    public async Task<Result> DispatchEvent<TEvent>(TEvent @event, CancellationToken ct = default)
        where TEvent : IGameEvent
    {
        var results = await Task.WhenAll(
            _provider
                .GetServices<IGameResponder<TEvent>>()
                .Select(responder => responder.Respond(@event, ct))
        );

        return results.Length switch
        {
            0 => Result.FromSuccess(),
            1 => results[0],
            _ => new AggregateError(results.Cast<IResult>().ToArray()),
        };
    }
}
Do not follow this link