using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;
using System.Threading.Tasks;
namespace CoreCms.Net.Utility.Helper
{
///
/// 属性常用方法
///
public class AssemblyHelper
{
private static List? _allAssemblies = null;
///
/// 获取所有程序目录下和常用的程序集 包括一些系统引用程序集
///
/// 当前工程下的程序集
public static List GetAllAssembly()
{
if (_allAssemblies == null)
{
_allAssemblies = new List();
string? path = null;
string singlefile = null;
try
{
path = Assembly.GetEntryAssembly()?.Location;
}
catch { }
if (string.IsNullOrEmpty(path))
{
singlefile = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
path = Path.GetDirectoryName(singlefile);
}
if (string.IsNullOrEmpty(path))
throw new Exception("获取程序目录出错");
var dir = new DirectoryInfo(Path.GetDirectoryName(path) ?? "");
var dlls = dir.GetFiles("*.dll", SearchOption.TopDirectoryOnly);
string[] systemdll = new string[]
{
"Microsoft.",
"System.",
"Swashbuckle.",
"ICSharpCode",
"Newtonsoft.",
"Oracle.",
"Pomelo.",
"SQLitePCLRaw.",
"Aliyun.OSS",
"BouncyCastle.",
"FreeSql.",
"Google.Protobuf.dll",
"Humanizer.dll",
"IdleBus.dll",
"K4os.",
"MySql.Data.",
"Npgsql.",
"NPOI.",
"netstandard",
"MySqlConnector",
"VueCliMiddleware"
};
var filtered = dlls.Where(x => systemdll.Any(y => x.Name.StartsWith(y)) == false);
foreach (var dll in filtered)
{
try
{
AssemblyLoadContext.Default.LoadFromAssemblyPath(dll.FullName);
}
catch
{
}
}
var dlllist = AssemblyLoadContext.Default.Assemblies.Where(x => systemdll.Any(y => x.FullName.StartsWith(y)) == false).ToList();
_allAssemblies.AddRange(dlllist);
}
return _allAssemblies;
}
/// 获取需要更新或者是创建的 数据库表模型List
///
/// 继承表某个表的所有
///
///
///
///
public static Type[] DbCodeFirstModes (string ModeProjectName, string ModeNamespace = null, string ConfigId = null , Type subClass= null, Type thisAttribute=null)
{
#nullable enable
Type[]? types = GetAllAssembly().Where(x => x.FullName.Contains(ModeProjectName + ",")).FirstOrDefault()?.GetTypes().WhereIF(!string.IsNullOrEmpty(ModeNamespace), name => name.FullName.Contains(ModeNamespace + ".")).ToArray()
.WhereIF(subClass!=null, x => x.IsSubclassOf(subClass)).ToArray()
.WhereIF(thisAttribute!=null,x =>( x.GetCustomAttributes(thisAttribute,true).Length>0)).ToArray();
return types;
}
}
}