using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Linq;
using System.Reflection;
namespace RainOpsMini.Plugins
{
public static class PluginRegistrationExtensions
{
///
/// 自动扫描并注册所有实现了 IPlugin 接口的插件
///
/// 服务集合
/// 服务集合
public static IServiceCollection AddAllPlugins(this IServiceCollection services)
{
// 获取当前程序集中所有实现了 IPlugin 接口且不是抽象类的类型
var pluginTypes = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => typeof(IPlugin).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract);
foreach (var type in pluginTypes)
{
// 1. 注册自身类型为 Singleton
services.AddSingleton(type);
// 2. 注册为 IPlugin 接口 (使用同一个实例)
services.AddSingleton(typeof(IPlugin), sp => sp.GetRequiredService(type));
// 3. 如果是后台服务 (BackgroundService 或 IHostedService),注册为 HostedService (使用同一个实例)
if (typeof(IHostedService).IsAssignableFrom(type))
{
services.AddSingleton(sp => (IHostedService)sp.GetRequiredService(type));
}
}
// 注册插件管理器
services.AddSingleton();
return services;
}
}
}