LFlow/LFlow.InternalEventBus/InternalEventBusExtensions.cs

67 lines
2.5 KiB
C#

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<Type, IInternalEventSubscriber> _eventSubscribers = new();
private static readonly ConcurrentBag<Type> _eventSubscriberTypes = [];
/// <summary>
/// 添加事件订阅服务
/// </summary>
/// <param name="services"></param>
/// <param name="assemblies"></param>
public static void AddInternalEventBus(this IServiceCollection services, List<Assembly> 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);
}
}
});
}
/// <summary>
/// 构建事件对象列表
/// </summary>
/// <param name="app"></param>
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);
});
}
/// <summary>
/// 启用内部事件
/// </summary>
/// <param name="app"></param>
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);
}
});
}
}
}