|
| 1 | +using McMaster.NETCore.Plugins; |
| 2 | +using Microsoft.Extensions.DependencyInjection; |
| 3 | +using System; |
| 4 | +using System.IO; |
| 5 | +using System.Linq; |
| 6 | +using System.Reflection; |
| 7 | +using System.Text.Json; |
| 8 | + |
| 9 | +namespace FaasNet.Plugin |
| 10 | +{ |
| 11 | + public class PluginEntryDiscovery |
| 12 | + { |
| 13 | + public static bool TryExtract(string pluginDirectoryPath, out IDiscoveredPlugin discoveryPlugin) |
| 14 | + { |
| 15 | + discoveryPlugin = null; |
| 16 | + var appsettingsFilePath = Path.Combine(pluginDirectoryPath, "appsettings.json"); |
| 17 | + if (!File.Exists(appsettingsFilePath)) return false; |
| 18 | + var pluginEntry = JsonSerializer.Deserialize<PluginEntry>(File.ReadAllText(appsettingsFilePath)); |
| 19 | + var dllPath = Path.Combine(pluginDirectoryPath, pluginEntry.DllName); |
| 20 | + if(!File.Exists(dllPath)) return false; |
| 21 | + var loader = PluginLoader.CreateFromAssemblyFile( |
| 22 | + dllPath, |
| 23 | + sharedTypes: new[] { typeof(IPlugin<>), typeof(IServiceCollection) }); |
| 24 | + var assembly = loader.LoadDefaultAssembly(); |
| 25 | + var types = assembly.GetTypes(); |
| 26 | + var pluginType = types.FirstOrDefault(t => t.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition().Name.StartsWith("IPlugin"))); |
| 27 | + if (pluginType == null) return false; |
| 28 | + var optionType = pluginType.GetInterfaces()[0].GenericTypeArguments[0]; |
| 29 | + dynamic option = Activator.CreateInstance(optionType); |
| 30 | + var serializedConfiguration = string.Empty; |
| 31 | + if(pluginEntry.Configuration != null) serializedConfiguration = JsonSerializer.Serialize(pluginEntry.Configuration); |
| 32 | + if(!string.IsNullOrWhiteSpace(serializedConfiguration)) option = JsonSerializer.Deserialize(serializedConfiguration, optionType, new JsonSerializerOptions |
| 33 | + { |
| 34 | + PropertyNameCaseInsensitive = true |
| 35 | + }); |
| 36 | + discoveryPlugin = new DiscoveredPlugin(pluginType, option); |
| 37 | + return true; |
| 38 | + } |
| 39 | + |
| 40 | + private class DiscoveredPlugin : IDiscoveredPlugin |
| 41 | + { |
| 42 | + private readonly Type _pluginType; |
| 43 | + private readonly dynamic _option; |
| 44 | + |
| 45 | + public DiscoveredPlugin(Type pluginType, dynamic option) |
| 46 | + { |
| 47 | + _pluginType = pluginType; |
| 48 | + _option = option; |
| 49 | + } |
| 50 | + |
| 51 | + public void Load(IServiceCollection services) |
| 52 | + { |
| 53 | + var pluginInstance = Activator.CreateInstance(_pluginType); |
| 54 | + var loadFn = _pluginType.GetMethod("Load", BindingFlags.Public | BindingFlags.Instance); |
| 55 | + loadFn.Invoke(pluginInstance, new object[] { services, _option }); |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + public interface IDiscoveredPlugin |
| 61 | + { |
| 62 | + void Load(IServiceCollection services); |
| 63 | + } |
| 64 | +} |
0 commit comments