C#C
C#2y ago
Pdawg

Plugin system not casting properly

I'm trying to make a plugin system for my app, which does this:
public void LoadAndRunPlugins()
{
    foreach (string dllFile in Directory.GetFiles(pluginDirectory, "*.dll"))
    {
        try
        {
            Assembly assembly = pluginLoadContext.LoadFromAssemblyPath(Path.GetFullPath(dllFile));

            foreach (Type type in assembly.GetTypes().Where(asm => !asm.FullName.Contains("GyroShell.Library")))
            {
                if (type.GetInterface("IPlugin") != null)
                {
                    IPlugin plugin = Activator.CreateInstance(type) as IPlugin;
                    plugin.Initialize();
                }
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine($"[-] PluginManager: Error loading and running plugin from {dllFile}: {ex.Message}");
        }
    }
}

The
IPlugin
instance is null, so calling
plugin.Initialize()
throws an NRE. The thing is, it should work just fine, given my plugin code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GyroShell.Library.Interfaces;

namespace TestGyroShellModule
{
    public class PluginRoot : IPlugin
    {
        //public IPluginInfo PluginInformation => new PluginInfo();

        public void Initialize()
        {
            Debug.WriteLine("We're alive from test plugin!");
        }

        public void Shutdown()
        {
            // Shutdown logic
        }

        /*private class PluginInfo : IPluginInfo
        {
            public string Name => "Test GyroShell Plugin";
        }*/
    }
}

And yes, they both reference the same exact interface, defined in
GyroShell.Library.Interfaces
.

Lastly, I've tried debugging this and nothing should go wrong. It tries to cast the
PluginRoot
class to an
IPlugin
, which should work since it properly implements the interface, but it just fails. No exceptions are thrown.
Was this page helpful?