Skip to content

Commit 1496b2f

Browse files
committed
event dispatcher
1 parent 92dfba6 commit 1496b2f

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
using Disc.NET.Handlers;
2+
using Disc.NET.Shared.Configurations;
3+
using Disc.NET.Shared.Enums;
4+
using System.Reflection;
5+
using System.Text.Json;
6+
7+
namespace Disc.NET.Dispatcher
8+
{
9+
internal class EventDispatcher
10+
{
11+
private readonly List<IHandler> _handlers;
12+
13+
private readonly AppConfiguration _appConfiguration;
14+
public EventDispatcher(AppConfiguration appConfiguration)
15+
{
16+
_appConfiguration = appConfiguration;
17+
_handlers = Assembly.GetExecutingAssembly().GetTypes()
18+
.Where(t => typeof(IHandler).IsAssignableFrom(t)
19+
&& !t.IsInterface
20+
&& !t.IsAbstract)
21+
.Select(t => (IHandler)Activator.CreateInstance(t, appConfiguration)!)
22+
.ToList();
23+
}
24+
public async Task DispatchAsync(EventHandlerPayload payload)
25+
{
26+
var eventType = payload.EventType;
27+
var handlers = _handlers.Where(x => x.GetEventType() == eventType).ToList();
28+
foreach (var handler in handlers)
29+
{
30+
await handler.HandleAsync(payload.Data, _appConfiguration);
31+
}
32+
}
33+
}
34+
35+
internal class EventHandlerPayload(GatewayEvent eventType, JsonDocument data)
36+
{
37+
public GatewayEvent EventType { get; } = eventType;
38+
public JsonDocument Data { get; } = data;
39+
40+
}
41+
}

0 commit comments

Comments
 (0)