Question

I'm creating an add-on system for a shell I'm developing using C#. I've followed this and this. Here is my function to load an add-on:

public void loadAppFromDLL(string assemblyFile)
{
    Assembly a = Assembly.Load(assemblyFile);
    Type app = a.GetType("App");
    MethodInfo loadMethod = app.GetMethod("load");
    object appInstance = Activator.CreateInstance(app);
    loadMethod.Invoke(appInstance, null);
}

Here is the add-on:

using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace App
{
    public class App
    {
        public void load()
        {
            MessageBox.Show("Application loaded successfully!");
        }
    }
}

When I build the add-on, I place it in the same directory as the shell executable and call:

LoadExternalApp lea = new LoadExternalApp();
lea.loadAppFromDLL("SampleApp");

(LoadExternalApp contains the DLL loading function)

When I was debugging my shell, I noticed that:

  1. The app didn't start
  2. There was a System.NullReferenceException

What am I not doing right?

Was it helpful?

Solution

This:

Type app = a.GetType("App");

is looking for a type with a namespace-qualified name of App.

Your type is called App in a namespace of App, so Assembly.GetType is returning null, and then you're dereferencing it. Instead, you should use:

Type app = a.GetType("App.App");

However, you shouldn't give a class the same name as its namespace in the first place. Fix that, so that you end up with something more like:

Type app = a.GetType("App.PlugIn");

You should still check whether GetType (or GetMethod) returns null, in order to fail rather more gracefully and with more information.

Additionally, you should start following .NET naming conventions - give methods names in PascalCase. Oh, and you might want to consider a common interface for your add-ins rather than relying on reflection to call methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top