Utilizzare la reflection per caricare dei plugin

Scritto da  Daniele Rongione il domenica 31 ottobre 2010  •  Linguaggio: C#,VB   • Livello: 100


Tramite il namespace System.Reflection è possibile caricare degli assembly a runtime e istanziarne le classi potendo, quindi, creare un sistema di plugin per la nostra applicazione.
Gli assembly da usare come plugin dovranno contenere l'implementazione delle interfacce definite nell'applicazione. Per caricare il plugin e istanziarne la classe corretta si può usare questo codice:

C#

string assemblyName = "DomusDotNet.Esempi.Reflection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
string interfaccia = "IEsempio";
object istanza = null;
// Carico l'assembly
System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(assemblyName);
// Cerco in ogni tipo all'interno dell'assembly
foreach (Type type in assembly.GetTypes())
{
// Se il tipo è pubblico e non è astratto
if ((type.IsPublic) &&
!((type.Attributes & System.Reflection.TypeAttributes.Abstract) == System.Reflection.TypeAttributes.Abstract))
{
// Controllo che il tipo implementi l'interfaccia
Type implementazione = type.GetInterface(interfaccia, true);
if (implementazione != null)
{
// Istanzio la classe
istanza = assembly.CreateInstance(type.FullName);
}
}
}

 

VB.NET

Dim assemblyName As String = "DomusDotNet.Esempi.Reflection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
Dim interfaccia As String = "IEsempio"
Dim istanza As Object = Nothing

' Carico l'assembly
Dim assembly As System.Reflection.Assembly = System.Reflection.Assembly.Load(assemblyName)
' Cerco in ogni tipo all'interno dell'assembly
For Each type As Type In assembly.GetTypes()
' Se il tipo è pubblico e non è astratto
If (type.IsPublic) AndAlso Not ((type.Attributes And System.Reflection.TypeAttributes.Abstract) = System.Reflection.TypeAttributes.Abstract) Then
' Controllo che il tipo implementi l'interfaccia
Dim implementazione As Type = type.GetInterface(interfaccia, True)
If implementazione IsNot Nothing Then
' Istanzio la classe
istanza = assembly.CreateInstance(type.FullName)
End If
End If
Next


Tags: Reflection

 
x