using MAX.Core.Helpers; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; namespace MAX.Core.Reflections; public class Finder { /// /// 跳过的程序集 /// private const string SkipAssemblies = "^System|^Microsoft|^mscorlib|^netstandard|^Autofac|^AutoMapper|^EntityFramework|^Newtonsoft|^Castle|^NLog|^Pomelo|^AspectCore|^Xunit|^Nito|^Npgsql|^Exceptionless|^MySqlConnector|^Anonymously|^libuv|^api-ms|^clrcompression|^clretwrc|^clrjit|^coreclr|^dbgshim|^e_sqlite3|^hostfxr|^hostpolicy|^MessagePack|^mscordaccore|^mscordbi|^mscorrc|^sni|^sos|^SOS\\.NETCore|^sos_amd64|^SQLitePCLRaw|^StackExchange|^Swashbuckle|^WindowsBase|^ucrtbase|^DotNetCore\\.CAP|^MongoDB|^Confluent\\.Kafka|^librdkafka|^EasyCaching|^RabbitMQ|^Consul|^Dapper|^EnyimMemcachedCore|^Pipelines|^DnsClient|^IdentityModel|^zlib|^Runtime\\.|^Google|^Grpc|^Internal\\.|^Azure|^DevExpress\\.|^FreeSql\\.|^PresentationFramework|^PresentationCore|^Prism|^DirectWriteForwarder|^MAX\\.Common|^ReflectionHelperTypesPublicWrappers|^UIAutomation|^WindowsFormsIntegration"; /// /// 获取程序集列表 /// public virtual List GetAssemblies() { LoadAssemblies(AppDomain.CurrentDomain.BaseDirectory); return GetAssembliesFromCurrentAppDomain(); } /// /// 加载程序集到当前应用程序域 /// /// 目录绝对路径 protected void LoadAssemblies(string path) { foreach (string file in Directory.GetFiles(path, "*.dll")) { if (Match(Path.GetFileName(file)) == false) { continue; } LoadAssemblyToAppDomain(file, out _); } } /// /// 程序集是否匹配 /// protected virtual bool Match(string assemblyName) { return Regex.IsMatch(assemblyName, SkipAssemblies, RegexOptions.IgnoreCase | RegexOptions.Compiled) == false; } /// /// 将程序集添加当前应用程序域 /// protected Exception LoadAssemblyToAppDomain(string file, out Assembly assembly) { try { //Debug.WriteLine($"Load Assembly : {Path.GetFileName(file)}"); AssemblyName assemblyName = AssemblyName.GetAssemblyName(file); assembly = AppDomain.CurrentDomain.Load(assemblyName); return null; } catch (FileNotFoundException) { // 如果找不到文件,回退到 LoadFrom 方式 try { assembly = Assembly.LoadFrom(file); return null; } catch (Exception ex) { assembly = null; return ex; } } catch (Exception ex) { assembly = null; return ex; } } /// /// 从当前应用程序域获取程序集列表 /// private List GetAssembliesFromCurrentAppDomain() { List result = []; foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (Match(assembly)) { result.Add(assembly); } } return result.Distinct().ToList(); } /// /// 程序集是否匹配 /// private bool Match(Assembly assembly) { return !Regex.IsMatch(assembly.FullName, SkipAssemblies, RegexOptions.IgnoreCase | RegexOptions.Compiled); } /// /// 查找类型列表 /// /// 查找类型 /// 在指定的程序集列表中查找 public List Find(List assemblies = null) { return Find(typeof(T), assemblies); } /// /// 查找类型列表 /// /// 查找类型 /// 在指定的程序集列表中查找 public List Find(Type findType, List assemblies = null) { assemblies ??= GetAssemblies(); return ReflectionHelper.FindTypes(findType, assemblies.ToArray()); } }