简体   繁体   中英

Dynamically create class with Constructor that calls another Static class method

I'm trying to dynamically create an instance of class CommandDrawing which is in another assembly. The CommandDrawing class default constructor contains calls to static methods which are inanother another class in the same assembley. The dynamic class is created but when it trys to run the static method call in the constructor it falls over with exception:

Exception has been thrown by the target of an invocation. TypeInitializeException`The type initializer for threw an exception.

Do I have to load in both classes and if so how?

I use code below to create the class which I've used successfully before and works when the static method calls are not there:

Assembly assemblyCommandDrawing = System.Reflection.Assembly.LoadFile(@"D:\ManifoldInspections.dll");
Type typeCommandDrawing = assemblyCommandDrawing.GetType("InspectionDetails.CommandDrawing");
object cmd = System.Activator.CreateInstance (typeCommandDrawing, new object[] { drawing, DrawingBaseDetail });

The CommandDrawing default constructor looks like below - note UtilityMapControl.SetupDrawingTableTemplate is the static method I'm calling and it falls over here:

public CommandDrawing(Manifold.Interop.Drawing p_Drawing, InspectionDetails.DrawingBaseDetail p_ClassDetailTemplate)
{
  this.Drawing = p_Drawing;
  //this.ClassDetailTemplate = p_ClassDetailTemplate.GetType();
  this.ClassDetailTemplate = p_ClassDetailTemplate;
  ManifoldInspections.Utility.UtilityMapControl.SetupDrawingTableTemplate(this.Drawing, p_ClassDetailTemplate);
}

Maybe a dependency could not be loaded. If the type initializer uses a type from another Assembly that could happen, because LoadFile doesn't resolve dependencies as you might expect. MSDN says :

LoadFile does not load files into the LoadFrom context, and does not resolve dependencies using the load path, as the LoadFrom method does.

So i suggest using LoadFrom instead of LoadFile .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM