I have a solution with two assemblies, one of these is called Domain and contains a Book class and an Author class.
I want to dynamically create a class which inherits from the Book class. Here's my code:
public Book CreateBookProxy(Book book)
{
CSharpCodeProvider cscp = new CSharpCodeProvider(new Dictionary<String, String> { { "CompilerVersion", "v3.5" } });
var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll", "Domain.dll" }, "Proxies.dll", false);
parameters.GenerateExecutable = false;
var compileUnit = new CodeCompileUnit();
var ns = new CodeNamespace("Proxies");
compileUnit.Namespaces.Add(ns);
ns.Imports.Add(new CodeNamespaceImport("System"));
ns.Imports.Add(new CodeNamespaceImport("Domain"));
var classType = new CodeTypeDeclaration("BookProxy");
classType.Attributes = MemberAttributes.Public;
classType.BaseTypes.Add(new CodeTypeReference(typeof(Book)));
ns.Types.Add(classType);
var results = cscp.CompileAssemblyFromDom(parameters, compileUnit);
List<string> errors = new List<string>();
errors.AddRange(results.Errors.Cast<CompilerError>().Select(e => e.ErrorText));
return Activator.CreateInstance(Type.GetType("Proxies.BookProxy, Proxies")) as Book;
}
However I'm getting the following error:
Metadata file 'Domain.dll' could not be found
Domain.dll is referenced in my start up project so it exists in the bin folder at run time.
Interestingly Assembly.Load("Domain.dll"); throws a FileNotFoundException
How can I resolve this issue?
I would suggest explicitly specify the location of Domain.dll
as following:
parameters.ReferencedAssemblies.Add(typeof(<TYPE FROM DOMAIN.DLL>).Assembly.Location);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With