mirror of
https://gitee.com/xiarenalofs/squad-rain-ops-mini.git
synced 2026-08-06 21:36:25 +08:00
45 lines
1.6 KiB
C#
45 lines
1.6 KiB
C#
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Hosting;
|
|
using System;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
|
|
namespace RainOpsMini.Plugins
|
|
{
|
|
public static class PluginRegistrationExtensions
|
|
{
|
|
/// <summary>
|
|
/// 自动扫描并注册所有实现了 IPlugin 接口的插件
|
|
/// </summary>
|
|
/// <param name="services">服务集合</param>
|
|
/// <returns>服务集合</returns>
|
|
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<IHostedService>(sp => (IHostedService)sp.GetRequiredService(type));
|
|
}
|
|
}
|
|
|
|
// 注册插件管理器
|
|
services.AddSingleton<PluginManager>();
|
|
|
|
return services;
|
|
}
|
|
}
|
|
}
|