For my own amusement and to learn the C# reflection APIs, I’ve been toying with the idea of an useless application built completely out of plugins, such that the only thing done by the main program is to read a config file, and load a plugin that will proceed to load every other assembly it’s been configured to load on the fly.
To do this, I was thinking of using attributes to define (…)services(?) and events (for the sake of argument, let’s call them ServiceAttribute(string) EventAttribute(string), where the parameter is the name of the hook), and then keep a table of where we can find these. An example would be like this
namespace example{
public class Plugin : IPlugin{
[Service("myService")]
public void PrintFrickingEverything(params string[] toPrint){
foreach(string s in toPrint){
Console.WriteLine(s);
}
}
}
}
And the hook would be accessed somehow by asking for “example.Plugin.myService”
However, a couple of things stick in my head,
one: this implementation seems to be Martin Fowler’s service locator pattern, which I think it couples things too tightly together, and would rather avoid it if possible.
two: While I’ve done something similar to make a dispatcher for plugins in PHP, the type safety in C# makes this approach difficult.
I know I could use MS’s library for this kind of thing, but I want to build this from the ground up by myself so I can learn about it along way to help me with other things I want to write later on.
Anyway, tl;dr: I want to get past the typing system somehow and be able to keep these methods somewhere, yet still be able to call them without needing to resort to casting an array of objects. Is it possible?
YES.
What you are trying to do is how we did plugins years ago, and it works okay. Nowadays we have MEF to do it, however to learn I recommed taking a look at this: http://www.codeproject.com/Articles/6334/Plug-ins-in-C