Einzelnen Beitrag anzeigen

Elvis

Registriert seit: 25. Nov 2005
Ort: München
1.909 Beiträge
 
Delphi 2010 Professional
 
#4

Re: Klassenbiliothek (DLL) dynamisch Laden ?

  Alt 14. Jun 2007, 16:54
Obwohl du VB benutzt, will ich mal trotzdem was dazu schreiben[1].

Ich werde es in C# schreiben, sollte aber nachvollziehbar sein.

Man nehme 2 Assemblies.
Eine nennen wir einfach mal PluginRtl, die andere PluginLib.
In die PluginRtl packen wir ein Interface, welches durch die eigentliche Klasse im eigentlichen Plugin implementiert wird.
Warum erkläre ich später.

Die erste Assembly enthält nur das hier:
Code:
namespace PluginRtl
{
  public interface IMathDings
  {
    int Add(int left, int right);
  }
}
Die zweite Assembly setzt eine Referenz auf die erste und implementiert das Interface:
Code:
namespace PluginLib
{
  public sealed class MathDings : IMathDings
  {
    public int Add(int left, int right)
    {
       return left + right;
    }
  }
}
So nun noch schnell eine kleine Anwendung erzeugt, die wiederum die erste Assembly referenziert:
Code:
class Program
{
  static void Main()
  {
    Assembly plugin = Assembly.LoadFile("PluginLib.dll");
    Type mathDingsType = plugin.GetType("PluginRtl.MathDings");
    if(typeof(IMathDings).IsAssignableForm(mathDingsType))
    {
       IMathDings instance = Activator.CreateInstance(mathDingsType) as IMathDings;
       int result = instance.Add(1, 2);
    }
  }
}

Ist aber alles uncompiliert aus den Fingern gesaugt. Kleinere Ecken können also drin, aber es sollte trotzdem die Herangehensweise klar machen.
Das Interface in einer eigene Assembly hat den Grund, dass man so eine Stelle hat, gegen die man kompilieren kann, aber trotzdem noch die Implementierung wechseln kann.





[1] Vielleicht wirst du ja gezwungen und kannst nix dafür...
Robert Giesecke
I’m a great believer in “Occam’s Razor,” the principle which says:
“If you say something complicated, I’ll slit your throat.”
  Mit Zitat antworten Zitat