Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Metadata file 'Domain.dll' could not be found when using CSharpCodeProvider referencing project

Tags:

c#

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?

like image 530
Liath Avatar asked Aug 13 '13 16:08

Liath


1 Answers

I would suggest explicitly specify the location of Domain.dll as following:

parameters.ReferencedAssemblies.Add(typeof(<TYPE FROM DOMAIN.DLL>).Assembly.Location);
like image 65
Alexander Manekovskiy Avatar answered Nov 03 '22 05:11

Alexander Manekovskiy