I have an application (let’s just call it MyApp) that dynamically creates the source code for the class and then compiles it. When it compiles the source code, I also refer to another DLL (this is the base class for this newly created class), which already exists in another folder. To compile and output the DLL, I do the following:
//Create a C# code provider CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); //Set the complier parameters CompilerParameters cp = new CompilerParameters(); cp.GenerateExecutable = false; cp.GenerateInMemory = false; cp.TreatWarningsAsErrors = false; cp.WarningLevel = 3; cp.OutputAssembly = "SomeOutputPathForDLL"; // Include referenced assemblies cp.ReferencedAssemblies.Add("mscorlib.dll"); cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("System.Core.dll"); cp.ReferencedAssemblies.Add("System.Data.dll"); cp.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll"); cp.ReferencedAssemblies.Add("System.Xml.dll"); cp.ReferencedAssemblies.Add("System.Xml.Linq.dll"); cp.ReferencedAssemblies.Add("MyApp.exe"); cp.ReferencedAssemblies.Add("SomeFolder\SomeAdditionalReferencedDLL.dll"); // Set the compiler options cp.CompilerOptions = "/target:library /optimize"; CompilerResults cr = provider.CompileAssemblyFromFile(cp, "PathToSourceCodeFile");
Later in my application (or the next time the application starts) I try to create an instance of the class. I know where the DLL is for the newly created class (let it be called Blah), and the base class. I use the following code to try to instantiate a new class:
Assembly assembly = Assembly.LoadFile("PathToNewClassDLL"); Blah newBlah = assembly.CreateInstance("MyApp.BlahNamespace.Blah") as Blah;
When I call Assembly.CreateInstance, as I do above, I get a message that it cannot create an instance. When I check assembly.GetReferencedAssemblies (), it has standard links and a link for my application (MyApp.exe), but it does not have a reference to the dependent base class that I used when compiling the class initially (SomeAdditionalReferencedDLL.dll).
I know that I need to somehow add a reference to the base class to create an instance, but I'm not sure how to do it. How to create an instance of a class from an assembly when I have an assembly and all its dependencies?
thanks
Dan
source share