Ryan Bennett Ryan Bennett -3 years ago 110
C# Question

Reflection - Can't create a new object instance C#

I am trying to create a plug-in type archetecure for my project. I would like the ability to load an assembly, get a type that is derived from an abstract base class in my project, instantiate it and load that derived type into the main processing object.

My problem right now is that when I instantiate the object from the reflected assembly, it is always null. I feel that the problem may lie in the fact that the referenced assembly has 3rd party dlls that it is using. Here is the code: the only exception that gets hit is the final one.

static void Main(string[] args)
string engineFilePath = ConfigurationManager.AppSettings["EngineFilesDirectory"]
+ "\\" + ConfigurationManager.AppSettings["EngineDllFileName"];
Assembly asm = Assembly.LoadFile(engineFilePath);

Type engineType = asm.GetType(ConfigurationManager.AppSettings["EngineType"]);

if (!engineType.IsSubclassOf(typeof(EngineConcrete)))
throw new ArgumentException("Engine is not derived from base implimentation.");

object engineInstance = asm.CreateInstance(engineType.Namespace + "." + engineType);

if (engineInstance == null)
//always thrown at this point
throw new Exception(string.Format("Engine object is null."));


If I change the instantiation line to
, I receive an error saying that one of the 3rd party dll's being referenced by the reflected assembly can't be found, though they are in the same directory as the .dll being reflected.

There is a public constructor for the type that is being reflected as well. It has no parameters and inherits from the

Answer Source

I think null is what you get when the type can't be found; the namespace name plus the type name may not be sufficient (strong naming issues). What happens if you put the 3rd-party dlls in the directory of the executing application, not the directory of the plugin?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download