C # calling a static method at runtime without reference to build time?

I am writing a system in C # .net (2.0). It has a plug-in modular architecture. Assemblies can be added to the system without rebuilding the base modules. To connect to the new module, I want to try to call the static method in another module by name. I do not want the called module to be referenced in any way during the build.

Back when I wrote unmanaged code, starting with the path to the .dll file, I would use LoadLibrary () to get the .dll into memory, and then use get GetProcAddress () to get the pointer to the function I wanted to call. How to achieve the same result in C # /. NET.

+6
source share
2 answers

After assembling the assembly using Assembly.LoadFrom (...) you can get the type by name and get some static method:

Type t = Type.GetType(className); // get the method MethodInfo method = t.GetMethod("MyStaticMethod",BindingFlags.Public|BindingFlags.Static); Then you call the method: method.Invoke(null,null); // assuming it doesn't take parameters 
+16
source share

here is a sample:

  string assmSpec = ""; // OS PathName to assembly name... if (!File.Exists(assmSpec)) throw new DataImportException(string.Format( "Assembly [{0}] cannot be located.", assmSpec)); // ------------------------------------------- Assembly dA; try { dA = Assembly.LoadFrom(assmSpec); } catch(FileNotFoundException nfX) { throw new DataImportException(string.Format( "Assembly [{0}] cannot be located.", assmSpec), nfX); } // ------------------------------------------- // Now here you have to instantiate the class // in the assembly by a string classname IImportData iImp = (IImportData)dA.CreateInstance ([Some string value for class Name]); if (iImp == null) throw new DataImportException( string.Format("Unable to instantiate {0} from {1}", dataImporter.ClassName, dataImporter.AssemblyName)); // ------------------------------------------- iImp.Process(); // Here you call method on interface that the class implements 
+1
source share

All Articles