tags:

views:

373

answers:

2

I am writing a system in C# .net (2.0). It has a pluggable module sort of architecture. Assemblies can be added to the system without rebuilding the base modules. To make a connection to the new module, I wish to attempt to call a static method in some other module by name. I do not want the called module to be referenced in any manner at build time.

Back when I was writing unmanaged code starting from the path to the .dll file I would use LoadLibrary() to get the .dll into memory then use get GetProcAddress() get a pointer to the function I wished to call. How do I achieve the same result in C# / .NET.

+9  A: 

After the assembly is loaded using Assembly.LoadFrom(...), you can get the type by name and get any 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
Philippe Leybaert
+2  A: 

here's 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
Charles Bretana
Code for calling an instance method. I asked for static method. But, I'll be needing this fragment eventually. Thanks. +1
rschuler