using LFlow.InternalEventBus.Interface; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using System.Collections.Concurrent; using System.Reflection; namespace LFlow.InternalEventBus { public static class InternalEventBusExtensions { private static readonly ConcurrentDictionary _eventSubscribers = new(); private static readonly ConcurrentBag _eventSubscriberTypes = []; /// /// 添加事件订阅服务 /// /// /// public static void AddInternalEventBus(this IServiceCollection services, List assemblies) { assemblies?.ForEach(assembly => { var types = assembly.GetTypes().ToList(); foreach (var type in types) { if (type.GetInterface(nameof(IInternalEventSubscriber)) != null) { services.AddSingleton(type); _eventSubscriberTypes.Add(type); } } }); } /// /// 构建事件对象列表 /// /// private static void BuildInternalEventBusServiceProvider(this IApplicationBuilder app) { var serviceProvider = app.ApplicationServices; _eventSubscriberTypes.ToList().ForEach(type => { if (serviceProvider.GetService(type) is IInternalEventSubscriber subscriber) _eventSubscribers.TryAdd(type, subscriber); }); } /// /// 启用内部事件 /// /// public static void UseInternalEventBus(this IApplicationBuilder app) { // build serviceProvider and eventSubscribers app.BuildInternalEventBusServiceProvider(); // sort by priority var orderedSubscribers = _eventSubscribers.Values.OrderBy(t => t?.Priority ?? 0).ToList(); orderedSubscribers.ForEach(subscriber => { if (subscriber is IInternalEventSubscriber eventSubscriber) { InternalEventBus.Register(eventSubscriber.EventName, eventSubscriber); } }); } } }