1

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?

RB.
  • 33,692
  • 12
  • 79
  • 121
Igor
  • 527
  • 2
  • 7
  • 22
  • Have you looked into the Managed Extensibility Framework? Microsoft have already written a pretty decent plugin-system for you ;-) – RB. Feb 19 '13 at 14:06
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Feb 19 '13 at 14:08

1 Answers1

2

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.

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929