ql_apimanager_backend/Apimanager_backend/Services/PluginLoaderService.cs

63 lines
2.0 KiB
C#

using Apimanager_backend.Data;
using Public;
using System.Reflection;
namespace Apimanager_backend.Services
{
// PluginLoaderService.cs
public class PluginLoaderService
{
private readonly IWebHostEnvironment _env;
private readonly ILogger<PluginLoaderService> _logger;
public PluginLoaderService(
IWebHostEnvironment env,
ILogger<PluginLoaderService> logger)
{
_env = env;
_logger = logger;
}
public void LoadPlugins(IServiceCollection services)
{
var pluginsDir = Path.Combine(_env.ContentRootPath, "ApiHandler");
Directory.CreateDirectory(pluginsDir);
foreach (var dllPath in Directory.GetFiles(pluginsDir, "*.dll"))
{
try
{
var assembly = LoadPluginAssembly(dllPath);
RegisterPluginServices(assembly, services);
_logger.LogInformation($"已加载插件: {Path.GetFileName(dllPath)}");
}
catch (Exception ex)
{
_logger.LogError(ex, $"加载插件失败: {dllPath}");
}
}
}
private Assembly LoadPluginAssembly(string dllPath)
{
// 使用隔离的加载上下文
var loadContext = new PluginLoadContext(dllPath);
return loadContext.LoadFromAssemblyPath(dllPath);
}
private void RegisterPluginServices(Assembly assembly, IServiceCollection services)
{
foreach (var type in assembly.GetTypes())
{
if (typeof(IBillableApiHandler).IsAssignableFrom(type) &&
!type.IsInterface &&
!type.IsAbstract)
{
services.AddTransient(typeof(IBillableApiHandler), type);
services.AddTransient(type); // 同时注册具体类型
}
}
}
}
}