1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| static void Main(string[] args)
{
Func<Type, bool> PluginTypeSelector = t => (t.GetCustomAttributes(typeof(PluginAttribute), false).FirstOrDefault() != default(Type));
var pluginTypes = Assembly.GetExecutingAssembly().
GetTypes().
Where(PluginTypeSelector);
/* on liste et instancie les plugin */
foreach (Type pluginType in pluginTypes)
{
PluginAttribute pluginAttr = (PluginAttribute)pluginType.GetCustomAttributes(typeof(PluginAttribute), false).First();
string pluginName = pluginAttr.PluginName;
// on vérifioe la validité du plugin => implémente-t-il l'interface ?
if(typeof(IPlugin).IsAssignableFrom(pluginType) == false)
{
Console.WriteLine(pluginName + " est invalide !!!");
continue;
}
Console.WriteLine("Instanciation Plugin : {0} ", pluginName); ;
IPlugin aPLugin = (IPlugin) Activator.CreateInstance(pluginType);
Console.WriteLine("Appel Plugin : {0} résultat {1} ", pluginName, aPLugin.SampleMethod()); ;
}
}
public interface IPlugin
{
int SampleMethod();
}
[Plugin("Mon Plugin")]
public class MyPlugin : IPlugin
{
public int SampleMethod()
{
return 42;
}
}
[Plugin("Mon Autre Plugin")]
public class MyPlugin2 : IPlugin
{
public int SampleMethod()
{
return 9999;
}
}
[AttributeUsage(AttributeTargets.Class)]
public class PluginAttribute : Attribute
{
public readonly string PluginName;
public PluginAttribute(string pluginName)
{
PluginName = pluginName;
}
} |