
Caricare una DLL dinamicamente (.NET 8)
Un esempio in .NET 8 su come è possibile caricare una DLL (Dynamic-Link Library) dinamicamente a runtime ed eseguire un metodo statico di una specifica classe.
C#: Assembly.LoadFile
const string CLASS_NAME = "Startup";
const string METHOD_NAME = "Init";
string repositoryName = ".\\ReactApp1.Server.Repositories.Sqlite.dll";
// se il percorso è relativo lo trasformo in assoluto
string fullRepositoryName = repositoryName.StartsWith('.')
? Path.Combine(AppContext.BaseDirectory, repositoryName)
: repositoryName;
// carico l'assembly tramite il suo percorso completo
Assembly? assembly = Assembly.LoadFile(fullRepositoryName) ?? throw new Exception($"Assembly '{repositoryName}' not found.");
// trovo la classe che mi interessa
dynamic? myClass = assembly.ExportedTypes.FirstOrDefault(x => x.Name == CLASS_NAME) ?? throw new Exception($"Class '{CLASS_NAME}' not found in the assembly '{repositoryName}'.");
// cerco il metodo statico che voglio invocare
MethodInfo staticMethodInfo = myClass.GetMethod(METHOD_NAME) ?? throw new Exception($"Method {CLASS_NAME}.{METHOD_NAME} not found in the assembly {repositoryName}.");
// invoco il metodo statico
staticMethodInfo.Invoke(null, [builder]);