You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
65 lines
2.4 KiB
65 lines
2.4 KiB
using Serilog;
|
|
using System;
|
|
using System.Collections.Concurrent;
|
|
using Wood.EventBus.Events;
|
|
using Wood.Util;
|
|
|
|
namespace Wood.EventBus
|
|
{
|
|
public class InMemoryEventBus : IEventBus
|
|
{
|
|
private readonly ConcurrentDictionary<string, List<object>> _handlersMap = new();
|
|
|
|
public void Subscribe<T, TH>(TH handler) where T : IntegrationEvent where TH : IIntegrationEventHandler<T>
|
|
{
|
|
var eventName = typeof(T).Name;
|
|
if (!_handlersMap.TryGetValue(eventName, out var handlers))
|
|
{
|
|
handlers = new List<object>();
|
|
_handlersMap.TryAdd(eventName, handlers);
|
|
}
|
|
handlers.Add(handler);
|
|
}
|
|
|
|
public void Unsubscribe<T, TH>() where T : IntegrationEvent where TH : IIntegrationEventHandler<T>
|
|
{
|
|
var eventName = typeof(T).Name;
|
|
if (_handlersMap.TryGetValue(eventName, out var handlers))
|
|
{
|
|
handlers.RemoveAll(h => h is TH);
|
|
}
|
|
}
|
|
|
|
public async Task PublishAsync<T>(T @event) where T : IntegrationEvent
|
|
{
|
|
var eventName = typeof(T).Name;
|
|
if (_handlersMap.TryGetValue(eventName, out var handlers))
|
|
{
|
|
foreach (var handler in handlers)
|
|
{
|
|
var methodInfo = handler.GetType().GetMethods().FirstOrDefault(m => m.Name == "Handle" && m.GetParameters().Length == 1 && m.GetParameters()[0].ParameterType == typeof(T));
|
|
if (methodInfo != null)
|
|
{
|
|
await (Task)methodInfo.Invoke(handler, new object[] { @event })!;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
public void Publish<T>(T @event) where T : IntegrationEvent
|
|
{
|
|
var eventName = typeof(T).Name;
|
|
if (_handlersMap.TryGetValue(eventName, out var handlers))
|
|
{
|
|
foreach (var handler in handlers)
|
|
{
|
|
var methodInfo = handler.GetType().GetMethods().FirstOrDefault(m => m.Name == "Handle" && m.GetParameters().Length == 1 && m.GetParameters()[0].ParameterType == typeof(T));
|
|
if (methodInfo != null)
|
|
{
|
|
methodInfo.Invoke(handler, new object[] { @event });
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|