Tuesday, March 15, 2011

C# polymorphism - load classes from DLL files

The responses I've got to this question have solved the problem I had in that question, but I'm wondering whether it's possible to extend it a bit. For example, if I were to have third parties contributing commands to this system, would there be a way of extending the first answer to my previous question to allow it to load all the commands from all the DLLs in a folder, and then list them in the list box.

Is that possible? Would it be able to work with a List of ICommand (as the answer to my previous question suggested).

From stackoverflow
  • You can load each assembly in a directory, iterate through each exposed class in the assembly, and then check for the implementation of your ICommand. From there you can then add them to your internal system by creating a new instance of those objects.

    Some places for error checking:

    • Assembly load, make sure it is CLR.
    • Construction: make sure it doesn't require any parameters and that it has a public constructor.
    • Construction: make sure it isn't an abstract class.
  • Yes.

     Assembly commandAssembly = Assembly.Load("some/path")
     var commands = new List<ICommand>();
    
     foreach (Type type in commandAssembly.GetTypes())
     {
        if (type.GetInterface(typeof(ICommand).FullName) != null)
        {
           commands.Add((ICommand)Activator.CreateInstance(type));
        }
     }
    

    However, you will probably run into some restrictions regarding assembly loading. You cannot just load assemblies from anywhere, otherwise you could reimplement something like COM DLL hell.

    Tom Anderson : Best practice for this type of loading would be to only load assemblies in a sub directory.

0 comments:

Post a Comment