namespace Admin.NET.Core.Service; /// /// 系统动态插件服务 /// [ApiDescriptionSettings(Order = 245)] public class SysPluginService : IDynamicApiController, ITransient { private readonly IDynamicApiRuntimeChangeProvider _provider; private readonly SqlSugarRepository _sysPluginRep; public SysPluginService(IDynamicApiRuntimeChangeProvider provider, SqlSugarRepository sysPluginRep) { _provider = provider; _sysPluginRep = sysPluginRep; } /// /// 获取动态插件列表 /// /// /// [DisplayName("获取动态插件列表")] public async Task> Page(PagePluginInput input) { return await _sysPluginRep.AsQueryable() .WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name)) .OrderBy(u => u.OrderNo) .ToPagedListAsync(input.Page, input.PageSize); } /// /// 增加动态插件 /// /// /// [ApiDescriptionSettings(Name = "Add"), HttpPost] [DisplayName("增加动态插件")] public async Task AddPlugin(AddPluginInput input) { var isExist = await _sysPluginRep.IsAnyAsync(u => u.Name == input.Name || u.AssemblyName == input.AssemblyName); if (isExist) throw Oops.Oh(ErrorCodeEnum.D1900); // 添加动态程序集/接口 input.AssemblyName = CompileAssembly(input.CsharpCode, input.AssemblyName); await _sysPluginRep.InsertAsync(input.Adapt()); } /// /// 更新动态插件 /// /// /// [ApiDescriptionSettings(Name = "Update"), HttpPost] [DisplayName("更新动态插件")] public async Task UpdatePlugin(UpdatePluginInput input) { var isExist = await _sysPluginRep.IsAnyAsync(u => (u.Name == input.Name || u.AssemblyName == input.AssemblyName) && u.Id != input.Id); if (isExist) throw Oops.Oh(ErrorCodeEnum.D1900); // 先移除再添加动态程序集/接口 RemoveAssembly(input.AssemblyName); input.AssemblyName = CompileAssembly(input.CsharpCode); await _sysPluginRep.AsUpdateable(input.Adapt()).IgnoreColumns(true).ExecuteCommandAsync(); } /// /// 删除动态插件 /// /// /// [ApiDescriptionSettings(Name = "Delete"), HttpPost] [DisplayName("删除动态插件")] public async Task DeletePlugin(DeletePluginInput input) { var plugin = await _sysPluginRep.GetByIdAsync(input.Id); if (plugin == null) return; // 移除动态程序集/接口 RemoveAssembly(plugin.AssemblyName); await _sysPluginRep.DeleteAsync(u => u.Id == input.Id); } /// /// 添加动态程序集/接口 /// /// /// 程序集名称 /// [DisplayName("添加动态程序集/接口")] public string CompileAssembly([FromBody] string csharpCode, [FromQuery] string assemblyName = default) { // 编译 C# 代码并返回动态程序集 var dynamicAssembly = App.CompileCSharpClassCode(csharpCode, assemblyName); // 将程序集添加进动态 WebAPI 应用部件 _provider.AddAssembliesWithNotifyChanges(dynamicAssembly); // 返回动态程序集名称 return dynamicAssembly.GetName().Name; } /// /// 移除动态程序集/接口 /// [ApiDescriptionSettings(Name = "RemoveAssembly"), HttpPost] [DisplayName("移除动态程序集/接口")] public void RemoveAssembly(string assemblyName) { _provider.RemoveAssembliesWithNotifyChanges(assemblyName); } }