using Microsoft.Extensions.Logging; using Pole.Core.Utils; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Text; using Microsoft.Extensions.DependencyInjection; using Pole.Core.EventBus.EventHandler; using System.Linq; using Pole.Core.Exceptions; namespace Pole.Core.EventBus { public class ObserverUnitContainer : IObserverUnitContainer { readonly ConcurrentDictionary> unitDict = new ConcurrentDictionary>(); public ObserverUnitContainer(IServiceProvider serviceProvider) { var eventHandlerList = new List<(Type, EventHandlerAttribute)>(); foreach (var assembly in AssemblyHelper.GetAssemblies(serviceProvider.GetService>())) { foreach (var type in assembly.GetTypes().Where(m => typeof(IPoleEventHandler).IsAssignableFrom(m) && m.IsClass && !m.IsAbstract && !typeof(Orleans.Runtime.GrainReference).IsAssignableFrom(m))) { var attribute = type.GetCustomAttributes(typeof(EventHandlerAttribute), false).FirstOrDefault(); var eventHandlerInterface = type.GetInterfaces().FirstOrDefault(type => typeof(IPoleEventHandler).IsAssignableFrom(type) && !type.IsGenericType); if (attribute != null) { eventHandlerList.Add((eventHandlerInterface, (EventHandlerAttribute)attribute)); } else { throw new PoleEventHandlerImplementException("Can not found EventHandlerAttribute in PoleEventHandler"); } } } foreach (var eventHandler in eventHandlerList) { var unitType = typeof(ObserverUnit<>).MakeGenericType(new Type[] { typeof(string) }); var unit = (ObserverUnit)Activator.CreateInstance(unitType, serviceProvider, eventHandler.Item1); unit.Observer(); Register(eventHandler.Item2.EventName, unit); } } public List> GetUnits(string observerName) { if (unitDict.TryGetValue(observerName, out var units)) return units.Select(m => (IObserverUnit)m).ToList(); else throw new UnfindObserverUnitException(observerName); } public List GetUnits(string observerName) { if (unitDict.TryGetValue(observerName, out var unit)) { return unit; } else throw new UnfindObserverUnitException(observerName); } public void Register(string observerName, IGrainID observerUnit) { if (unitDict.TryGetValue(observerName, out List units)) { units.Add(observerUnit); } if (!unitDict.TryAdd(observerName, new List { observerUnit })) { throw new ObserverUnitRepeatedException(observerUnit.EventHandlerType.FullName); } } } }