using Microsoft.Extensions.DependencyModel; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.Loader; using Znyc.Recruitment.Admin.Commons.Options; namespace Znyc.Recruitment.Admin.Commons.Helpers { /// /// public class RuntimeHelper { /// /// 获取项目程序集,排除所有的系统程序集(Microsoft.***、System.***等)、Nuget下载包 /// /// public static IList GetAllAssemblies() { List list = new List(); DependencyContext deps = DependencyContext.Default; //排除所有的系统程序集、Nuget下载包 IEnumerable libs = deps.CompileLibraries.Where(lib => lib.Type == AssembleTypeConsts.Project); //只获取本项目用到的包 foreach (CompilationLibrary lib in libs) { try { Assembly assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(lib.Name)); list.Add(assembly); } catch (Exception) { // ignored } } return list; } /// /// 获取项目程序集,排除所有的系统程序集(Microsoft.***、System.***等)、Nuget下载包和Znyc.Recruitment.Admin.Commons.dll /// 获取所有关于Znyc的程序集 /// /// public static IList GetAllZnycAssemblies() { List list = new List(); DependencyContext deps = DependencyContext.Default; //排除所有的系统程序集、Nuget下载包 IEnumerable libs = deps.CompileLibraries.Where(lib => lib.Type == AssembleTypeConsts.Project || lib.Name.StartsWith("Znyc")); //只获取本项目用到的包 foreach (CompilationLibrary lib in libs) { try { if (lib.Name != "Znyc.Recruitment.Admin.Commons") { Assembly assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(lib.Name)); list.Add(assembly); } } catch (Exception) { // ignored } } return list; } /// /// /// /// public static Assembly GetAssembly(string assemblyName) { return GetAllZnycAssemblies().FirstOrDefault(assembly => assembly.FullName.Contains(assemblyName)); } /// /// /// public static IList GetAllTypes() { List list = new List(); foreach (Assembly assembly in GetAllAssemblies()) { IEnumerable typeInfos = assembly.DefinedTypes; foreach (TypeInfo typeInfo in typeInfos) { list.Add(typeInfo.AsType()); } } return list; } /// /// /// /// public static IList GetTypesByAssembly(string assemblyName) { List list = new List(); Assembly assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(assemblyName)); IEnumerable typeInfos = assembly.DefinedTypes; foreach (TypeInfo typeInfo in typeInfos) { list.Add(typeInfo.AsType()); } return list; } /// /// 获取实现类 /// /// /// /// public static Type GetImplementType(string typeName, Type baseInterfaceType) { return GetAllTypes().FirstOrDefault(t => { if (t.Name == typeName && t.GetTypeInfo().GetInterfaces().Any(b => b.Name == baseInterfaceType.Name)) { TypeInfo typeInfo = t.GetTypeInfo(); return typeInfo.IsClass && !typeInfo.IsAbstract && !typeInfo.IsGenericType; } return false; }); } } }