views:

49

answers:

2

Hi, I'm a noob to this stuff. I want to make a C# program that uses plugins (as a way of learning). However, I don't understand where I'm going wrong here:

PluginClass = a.CreateInstance("MBPlugin");

PluginClass is of type Object. However it's always null. a is of type Assembly. The assembly definitely contains a class named MBPlugin. So what the hell?

+2  A: 

It would be unusual for the type to be called just MBPlugin with no namespace. You should provide the namespace-qualified name, e.g. "MyCompany.Plugins.MBPlugin".

Jon Skeet
Right, okay. So... Obviously I know the namespace here because I made the 'test plugin'... But how would you get the namespace in an assembly normally?
Motig
@Motig: That entirely depends on how your plugin would be configured. How would you even know the class name? It would be odd to require the plugin to be named with a particular name... I mean, you *could* look through the result of `Assembly.GetTypes()` and find a class with the right name, but it would be odd.
Jon Skeet
So how is this normally done?
Motig
@Motig: There are various different plugin mechanisms available, depending on how broadly you use the term "plugin". Some use extra configuration files, some detect assemblies based on folders and resolve the plugin dependencies via attributes. I agree with Martin's answer about using a plugin *interface* which can then be detected.
Jon Skeet
A: 

One approach I used for some projects:

Create an interface IPlugin which defines methods you're expecting for all plugins. In my case, this was mostly a Register() function which gave the plugin the opportunity to do whatever it had to do.

Then use Assembly.GetTypes to enumerate all types defined in the assembly and look for classes that define that interface (using typeof(IPlugin).IsAssignableFrom()). The go on and use these types.

Also you might want to have a look at frameworks like MEF which do (amongst other things) excatly what you want.

MartinStettner