JiShe.CollectBus/protocols/JiShe.CollectBus.Protocol/JiSheCollectBusProtocolModule.cs
2025-04-22 16:48:53 +08:00

71 lines
3.3 KiB
C#

using JiShe.CollectBus.Kafka.Internal;
using JiShe.CollectBus.Protocol.AnalysisData;
using JiShe.CollectBus.Protocol.Contracts.Abstracts;
using JiShe.CollectBus.Protocol.Contracts.Interfaces;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Serilog.Core;
using System.Reflection;
using TouchSocket.Core;
using Volo.Abp;
using Volo.Abp.Modularity;
namespace JiShe.CollectBus.Protocol
{
public class JiSheCollectBusProtocolModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddKeyedSingleton<IProtocolPlugin, StandardProtocolPlugin>(nameof(StandardProtocolPlugin));
RegisterProtocolAnalysis(context.Services);
}
public override async Task OnApplicationInitializationAsync(ApplicationInitializationContext context)
{
var standardProtocol = context.ServiceProvider.GetRequiredKeyedService<IProtocolPlugin>(nameof(StandardProtocolPlugin));
await standardProtocol.AddAsync();
}
public void RegisterProtocolAnalysis(IServiceCollection services)
{
// 批量注册
var assemblyPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
if (string.IsNullOrWhiteSpace(assemblyPath))
{
return;
}
var dllFiles = Directory.GetFiles(Path.Combine(assemblyPath, "Plugins") , "*.dll");
foreach (var file in dllFiles)
{
// 跳过已加载的程序集
var assemblyName = AssemblyName.GetAssemblyName(file);
var existingAssembly = AppDomain.CurrentDomain.GetAssemblies()
.FirstOrDefault(a => a.GetName().FullName == assemblyName.FullName);
var assembly = existingAssembly ?? Assembly.LoadFrom(file);
// 实现IAnalysisStrategy接口
//var analysisStrategyTypes = assembly.GetTypes().Where(t =>!t.IsAbstract && !t.IsInterface && t.GetInterfaces().Any(i =>
//i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAnalysisStrategy<,>))).ToList();
var analysisStrategyTypes = assembly.GetTypes().Where(type =>
typeof(IAnalysisStrategy<,>).IsAssignableFrom(type) &&
!type.IsAbstract && !type.IsInterface).ToList();
if (analysisStrategyTypes.Count == 0)
continue;
foreach (var analysisStrategyType in analysisStrategyTypes)
{
// 取所有接口
//var interfaceTypes = analysisStrategyType.GetInterfaces()
// .Where(i => i.IsGenericType &&
// i.GetGenericTypeDefinition() == typeof(IAnalysisStrategy<,>));
//foreach (var interfaceType in interfaceTypes)
//{
// services.AddKeyedTransient(analysisStrategyType, nameof(analysisStrategyType));
//}
services.AddKeyedTransient(analysisStrategyType, nameof(analysisStrategyType));
}
}
}
}
}