How to dynamically extend the C # class with new methods

advertisements

I'm building a website in ASP.NET that allows creating new modules based on a common class. The new modules need to have the ability to extend the base class with their own library of methods/functions. I would like to load all modules at Application_Start. They are identified by a unique string key.

The structure is something like this:

root

-Bin
--module1.dll
--module2.dll

-Modules
--module1
---mod.key1
--module2
---mod.key2

At startup each module folder is read and it's key identified, all settings loaded from db and common properties set, then stored in a collection. When a page is requested for a module, the base page class loads the appropriate module using it's unique directory key. Problem is the base module class does not contain the library of methods specific to that module (Only it's properties/settings loaded from db). How can I extend the module class to include methods during the module load at startup, or just instantiate the correct extended class dynamically using it's string name? or any other ideas? I don't want to hard code class names in the app load method so it can scale for future modules to be added.


There are several ways to do that. One way is to create a base class or interface from which to inherit, write your descendant classes in another DLL, and then use the Assembly.LoadFrom() method to load the appropriate classes from the DLL, as needed.

public MyType LoadTypeFromAssembly(string assemblyPath, string typeName)
{
            var assembly = Assembly.LoadFrom(assemblyPath);

            if (assembly == null)
                throw new InvalidOperationException("Could not load the specified assembly '" + assemblyPath + "'");

            var type = assembly.GetType(typeName);
            if (type == null)
                throw new InvalidOperationException("The specified class '" + typeName + "' was not found in assembly '" + assemblyPath  + "'");

            var instance = (MyType)Activator.CreateInstance(type);
            return instance;
}

Where MyType is the type of your base class or interface, and typeName is the name of your descendant class (that inherits from MyType).