Skip to content

Commit

Permalink
refactor: EntryPoint
Browse files Browse the repository at this point in the history
  • Loading branch information
LazuliKao committed Jul 22, 2023
1 parent 38334ef commit b632606
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 38 deletions.
16 changes: 14 additions & 2 deletions src/EntryPointAttribute.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,18 @@
namespace Loader;

[AttributeUsage(AttributeTargets.Method)]
public class EntryPointAttribute : Attribute
public abstract class EntryPointAttributeBase : Attribute
{
internal abstract IPlugin CreateInstance();
}

[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class EntryPointAttribute<T> : EntryPointAttributeBase
where T : IPlugin, new()
{
internal override IPlugin CreateInstance() => new T();
}

public interface IPlugin
{
void Initialize();
}
2 changes: 1 addition & 1 deletion src/Main.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace Loader;

public static class Main
{
[UnmanagedCallersOnly()]
[UnmanagedCallersOnly]
public static void Initialize()
{
DirectoryInfo directoryInfo = new("plugins");
Expand Down
64 changes: 29 additions & 35 deletions src/PluginManager.cs
Original file line number Diff line number Diff line change
@@ -1,36 +1,30 @@
using System.Reflection;
using System.Runtime.Loader;

namespace Loader;

internal static class PluginManager
{
public static List<AssemblyLoadContext> PluginContexts { get; }

static PluginManager()
{
PluginContexts = new();
}

public static bool LoadPlugin(string path)
{
AssemblyLoadContext loadContext = new(path);
Assembly assembly = loadContext.LoadFromAssemblyPath(path);
Type[] types = assembly.GetTypes();
foreach (Type type in types)
{
MethodInfo[] methods = type.GetMethods();
foreach (MethodInfo method in methods)
{
if (method.GetCustomAttribute<EntryPointAttribute>() is null || method.ReturnType is not null || method.GetParameters().LongLength > 0)
{
continue;
}
method.Invoke(null, null);
PluginContexts.Add(loadContext);
return true;
}
}
return false;
}
}
using System.Runtime.CompilerServices;
using System.Runtime.Loader;

namespace Loader;

internal static class PluginManager
{
public static List<(AssemblyLoadContext ctx, IPlugin plugin)> PluginContexts { get; }

static PluginManager()
{
PluginContexts = new();
}

public static bool LoadPlugin(string path)
{
AssemblyLoadContext loadContext = new(path);
Assembly assembly = loadContext.LoadFromAssemblyPath(path);
var success = false;
foreach (var entryPoint in assembly.GetCustomAttributes<EntryPointAttributeBase>())
{
var plugin = entryPoint.CreateInstance();
plugin.Initialize();
PluginContexts.Add((loadContext, plugin));
success = true;
}
return success;
}
}

0 comments on commit b632606

Please sign in to comment.