BotSharp/src/Infrastructure/BotSharp.Core/Infrastructures/PluginLoader.cs

73 lines
2.2 KiB
C#
Raw Normal View History

2023-06-26 22:16:21 +00:00
using Microsoft.AspNetCore.Builder;
2023-06-17 02:42:35 +00:00
using Microsoft.Extensions.Configuration;
2023-06-19 16:33:27 +00:00
using System.Drawing;
2023-06-17 02:42:35 +00:00
using System.IO;
using System.Reflection;
namespace BotSharp.Core.Infrastructures;
2023-06-17 02:42:35 +00:00
public class PluginLoader
{
private readonly IServiceCollection _services;
private readonly IConfiguration _config;
private readonly PluginLoaderSettings _settings;
private static List<IBotSharpPlugin> _modules = new List<IBotSharpPlugin>();
2023-06-26 22:16:21 +00:00
public PluginLoader(IServiceCollection services,
2023-06-17 02:42:35 +00:00
IConfiguration config,
PluginLoaderSettings settings)
{
_services = services;
_config = config;
_settings = settings;
}
2023-09-24 16:20:02 +00:00
public void Load(Action<Assembly> loaded)
2023-06-17 02:42:35 +00:00
{
var executingDir = Directory.GetParent(Assembly.GetEntryAssembly().Location).FullName;
_settings.Assemblies.ToList().ForEach(assemblyName =>
{
var assemblyPath = Path.Combine(executingDir, assemblyName + ".dll");
if (File.Exists(assemblyPath))
{
var assembly = Assembly.Load(assemblyName);
var modules = assembly.GetTypes()
.Where(x => x.GetInterface(nameof(IBotSharpPlugin)) != null)
.Select(x => Activator.CreateInstance(x) as IBotSharpPlugin)
.ToList();
foreach (var module in modules)
{
2023-08-31 02:09:38 +00:00
module.RegisterDI(_services, _config);
Console.WriteLine($"Loaded plugin {module.GetType().Name} from {assemblyName}.", Color.Green);
2023-06-17 02:42:35 +00:00
}
2023-09-24 16:20:02 +00:00
loaded(assembly);
2023-06-17 02:42:35 +00:00
_modules.AddRange(modules);
}
else
{
Console.WriteLine($"Can't find assemble {assemblyPath}.");
}
});
}
2023-06-26 22:16:21 +00:00
public void Configure(IApplicationBuilder app)
{
2023-08-31 02:09:38 +00:00
if (_modules.Count == 0)
2023-06-26 22:16:21 +00:00
{
Console.WriteLine($"No plugin loaded. Please check whether the Load() method is called.", Color.Yellow);
}
_modules.ForEach(module =>
{
if (module.GetType().GetInterface(nameof(IBotSharpAppPlugin)) != null)
{
2023-08-31 02:09:38 +00:00
(module as IBotSharpAppPlugin).Configure(app);
2023-06-26 22:16:21 +00:00
}
});
}
2023-06-17 02:42:35 +00:00
}