| | | 1 | | using Microsoft.Extensions.DependencyInjection; |
| | | 2 | | using Microsoft.SemanticKernel; |
| | | 3 | | |
| | | 4 | | using System.Diagnostics.CodeAnalysis; |
| | | 5 | | using System.Reflection; |
| | | 6 | | |
| | | 7 | | namespace NexusLabs.Needlr.SemanticKernel.PluginScanners; |
| | | 8 | | |
| | | 9 | | [RequiresUnreferencedCode("Service provider scanning uses reflection to discover types with [KernelFunction] methods.")] |
| | | 10 | | [RequiresDynamicCode("Service provider scanning uses reflection APIs that may require dynamic code generation.")] |
| | 4 | 11 | | internal sealed class ServiceProviderSemanticKernelPluginScanner( |
| | 4 | 12 | | IServiceProvider _root) : |
| | | 13 | | ISemanticKernelPluginScanner |
| | | 14 | | { |
| | | 15 | | public IReadOnlyList<Type> ScanForPluginTypes() |
| | | 16 | | { |
| | 4 | 17 | | var serviceCollection = _root.GetServiceCollection(); |
| | 4 | 18 | | var list = ScanForPluginTypes(serviceCollection) |
| | 880 | 19 | | .Where(t => serviceCollection.Any(sd => sd.ServiceType == t)) |
| | 4 | 20 | | .ToArray(); |
| | 4 | 21 | | return list; |
| | | 22 | | } |
| | | 23 | | |
| | | 24 | | private static IReadOnlyList<Type> ScanForPluginTypes(IServiceCollection serviceCollection) |
| | | 25 | | { |
| | 4 | 26 | | var list = serviceCollection |
| | 143 | 27 | | .Select(sd => sd.ServiceType) |
| | 143 | 28 | | .Where(t => t is { IsClass: true } && !t.IsAbstract) |
| | 4 | 29 | | .Where(HasKernelFunctions) |
| | 4 | 30 | | .Distinct() |
| | 4 | 31 | | .ToArray(); |
| | | 32 | | |
| | 4 | 33 | | return list; |
| | | 34 | | } |
| | | 35 | | |
| | | 36 | | private static bool HasKernelFunctions(Type t) => |
| | 107 | 37 | | t.GetMethods(BindingFlags.Instance | BindingFlags.Public) |
| | 638 | 38 | | .Any(m => m.IsDefined(typeof(KernelFunctionAttribute), inherit: true)); |
| | | 39 | | } |