if (!module_dir.Exists) throw new Exception("Modules directory does not exist.");
foreach (FileInfo f in module_dir.GetFiles("*.dll"))
{
Type t = Assembly.LoadFile(f.FullName).GetType();
baseModule m = Activator.CreateInstance(t) as baseModule;
if (m == null)
{
throw new Exception("dll is not of type IModule");
}
module_list.Add(m);
}
Unfortunately when I hit Activator.CreateInstance, I get the error :
"No parameterless constructor defined for this object."
Any ideas what I'm doing wrong?
AlanPosted Apr 18, 2008, 5:56 PM
You probably had it as private before so that the abstract class couldn't be instantiated.
However, that would have made the base class constructor inaccessible to TestModule's constructor and caused the error.
WesPosted Apr 18, 2008, 5:07 PM
Thanks!
AlanPosted Apr 18, 2008, 4:37 PM
If you haven't explicitly defined any constructors, then the system should provide TestModule with a public parameterless constructor and the abstract base class, baseModule, with a protected parameterless constructor. So, as long as the classes are public and they're not in a namespace, the code should work.
Is there anything which you're doing which is different to the above?
WesPosted Apr 18, 2008, 2:09 PM
AlanPosted Apr 18, 2008, 12:07 PM
The Assembly.LoadFile() method actually returns an Assembly object which doesn't have a public parameterless constructor - hence the error when you try to instantiate it.
Try this code instead:
Assembly asm = Assembly.LoadFile(f.FullName);
Type t = asm.GetType("TestModule"); // assuming no namespace
baseModule m = Activator.CreateInstance(t) as baseModule;