public sealed class EventProcessorFactory(IServiceProvider provider): IEventProcessorFactory
{
private static readonly Lazy<Dictionary<string, Type>> processors = new(DiscoverEventProcessors);
public IEventProcessor? GetProcessor(string eventName)
{
if(!processors.Value.TryGetValue(eventName, out var type))
return null;
return (IEventProcessor)provider.GetRequiredService(type);
}
private static Dictionary<string, Type> DiscoverEventProcessors()
{
var processorTypes = Assembly.GetExecutingAssembly().GetTypes()
.Where(t => typeof(IEventProcessor).IsAssignableFrom(t) && t.IsClass)
.ToArray();
var discoverEventProcessors = new Dictionary<string, Type>();
foreach(var processorType in processorTypes)
{
var handledEvents = processorType
.GetProperty(nameof(IEventProcessor.HandledEvents))
?.GetValue(null) as IReadOnlyCollection<string>;
foreach(var handledEvent in handledEvents ?? [])
discoverEventProcessors[handledEvent] = processorType;
}
return discoverEventProcessors;
}
}